【JS面试题】手写Promise加载图片

手写Promise加载一张图片

初始化:
1.html

<body>
    <script src="./promise.js"></script>
</body>

promise-demo.js

//手写promise加载图片
function loadImg(src) {
    const p = new Promise(
        (resolve, reject) => {
            const img = document.createElement('img')
            img.onload = () => {
                resolve(img)
            }
            img.onerror = () => {
                const err = new Error(`图片加载失败 ${src}`)
                reject(err)
            }
            img.src = src
        }
    )
    return p
}
const url = 'https://img.mukewang.com/5a9fc8070001a82402060220-140-140.jpg'

//执行函数,返回promise对象
loadImg(url).then(img => {
    console.log(img.width);
    return img
}).then(img => {
    console.log(img.height);
}).catch(ex => {console.error(ex)})

效果:
在这里插入图片描述
如果有错误时候:
【JS面试题】手写Promise加载图片_第1张图片

手写Promise加载多张图片

先加载第一个,在加载第二个

function loadImg(src) {
    const p = new Promise(
        (resolve, reject) => {
            const img = document.createElement('img')
            img.onload = () => {
                resolve(img)
            }
            img.onerror = () => {
                const err = new Error(`图片加载失败 ${src}`)
                reject(err)
            }
            img.src = src
        }
    )
    return p
}


const url1 = 'https://img.mukewang.com/5a9fc8070001a82402060220-140-140.jpg'
const url2 = 'https://img3.mukewang.com/5a9fc8070001a82402060220-100-100.jpg'

loadImg(url1).then(img1 => {
    console.log(img1.width)
    return img1 // 普通对象
}).then(img1 => {
    console.log(img1.height)
    return loadImg(url2) // promise 实例
}).then(img2 => {
    console.log(img2.width)
    return img2
}).then(img2 => {
    console.log(img2.height)
}).catch(ex => console.error(ex))

效果:
【JS面试题】手写Promise加载图片_第2张图片

你可能感兴趣的:(前端面试,JavaScript,javascript)