现在不会用Promise都不好意思说自己是前端,Promise为什么火起来,一句话解决了回调嵌套和执行顺序问题最重要的我感觉是解决顺序问题。
不过开始写之前我们先看看,promise怎么解决问题,怎么用。
列举一个顺序加载图片demo:
//需求 加载三张图片 img1,img2,img3,加载顺序是1,2,3
let url1 = "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3293635140,3955114282&fm=26&gp=0.jpg"
let url2 = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1019333328,1858047370&fm=26&gp=0.jpg"
let url3 = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=4226468334,723383513&fm=26&gp=0.jpg"
let oImg1 = new Image()
oImg1.onload = function() {
console.log('img1加载完毕')
let oImg2 = new Image()
oImg2.onload = function() {
console.log('img2加载完毕')
let oImg3 = new Image()
oImg3.onload = function() {
console.log('img3加载完毕')
console.log('全部加载完毕')
}
oImg3.src = url3
}
oImg2.src = url2
}
oImg1.src = url1
//结果没毛病
image.png
接下来我们试试promise怎么做,
function loadImg(url) {
let img = new Image()
img.src = url
return new Promise((resolve, reject) => {
img.onload = () => {
console.log(url)
resolve()
}
img.onerror = (e) => {
reject(e)
}
})
}
loadImg(url1).then(() => {
return loadImg(url2)
}).then(() => {
return loadImg(url3)
})
image.png
接下来再看看Promise.all,
//需求 加载三张图片 img1,img2 全部加载完成做一些事情
let urls = ["https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3293635140,3955114282&fm=26&gp=0.jpg",
"https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1019333328,1858047370&fm=26&gp=0.jpg"
]
function loadImg(url) {
let img = new Image()
img.src = url
return new Promise((resolve, reject) => {
img.onload = () => {
resolve(img)
}
img.onerror = (e) => {
reject(e)
}
})
}
function loadAll(arr) {
let result = []
arr.forEach(item => {
let p = loadImg(item).then((img) => {
console.log(img)
})
//存储当前Promise对象
console.log(p)
result.push(p)
});
Promise.all(result).then(() => {
//全部完成
console.log("done")
}).catch((err) => {
// 有失败的情况
console.log(err)
});
}
loadAll(urls)
image.png
完成。。。
网友评论