js promise

<html>

<head>
    <title>promise</title>
    <meta charset="utf-8">
    <style>

    </style>
</head>

<body>
    <h1>同步和異步 </h1>
    <P>同步會阻塞 異步不會阻塞</P>
    <P>異步用在網絡請求ajax setTimeout</P>
    <P>promise不是解決回調 是解決ajax多層嵌套</P>
</body>

</html>
<script src="../js/jquery.min.js"></script>
<script>
    //手寫promise 加載一張圖片

    function LoadImg(src) {
        return new Promise(
            (resolve, reject) => {
                const img = document.createElement('img')
                img.onload = () => {  //定義異步正常執行
                    resolve(img)
                }
                img.onerror = () => {
                    const err = new Error(`圖片加載失敗 ${src}`)
                    reject(img)
                }
                img.src = src; //立刻執行渲染顯示圖片
            }
        )
    }

    const src1 = 'http://a4.att.hudong.com/21/09/01200000026352136359091694357.jpg'
    const src2 = 'http://a1.att.hudong.com/05/00/01300000194285122188000535877.jpg'
    LoadImg(src1).then(img => {  //then 是promise的方法 resolve 的時候執行 catch 也是promise的方法 在reject的時候執行
        console.log(img.height)
        return img
    }).then((img) => {
        console.log(img.width)
        return LoadImg(src2)
    }).then((img) => {
        console.log(img.height)
        return img
    }).then((img) => {
        console.log(img.width)
    }).catch((err) => {
        console.log(err)
    })


</script>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章