当async/await碰见forEach-------------爆炸

let p = ['http://img3.imgtn.bdimg.com/it/u=3278834702,2663618759&fm=26&gp=0.jpg', 'http://img5.imgtn.bdimg.com/it/u=4180508012,1972588723&fm=15&gp=0.jpg', 'http://img10.360buyimg.com/n1/s350x449_jfs/t14989/169/1956143206/90455/a454f42c/5a657289N4b6344d4.jpg%21cc_350x449.jpg', 'http://b-ssl.duitang.com/uploads/item/201707/24/20170724135526_FCnkr.thumb.700_0.jpeg'];

function createImg(url) {
     
    return new Promise((resolve, reject) => {
     
        setTimeout(() => {
     
            let img = new Image();
            img.src = url;
            document.body.append(img)
            img.onload = () => {
     
                resolve(img)
            }
            img.onerror = () => {
     
                reject("加载失败")
            }
        }, 1000)
    })
}
# forEach代码
p.forEach(async (item) => {
     
    await createImg(item)
})
for循坏代码
async function run() {
     
    for (let i = 0; i < p.length; i++) {
     
        await createImg(p[i])
    }
}
run(

你可能感兴趣的:(js)