如今不會用Promise都很差意思說本身是前端,Promise爲何火起來,一句話解決了回調嵌套和執行順序問題最重要的我感受是解決順序問題。前端
不過開始寫以前咱們先看看,promise怎麼解決問題,怎麼用。
列舉一個順序加載圖片demo:promise
//需求 加載三張圖片 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
//結果沒毛病
url
接下來咱們試試promise怎麼作,spa
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) })
接下來再看看Promise.all,code
//需求 加載三張圖片 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)
完成。。。對象