??個(gè)人主頁:不叫貓先生
???♂?作者簡介:專注于前端領(lǐng)域各種技術(shù),熱衷分享,期待你的關(guān)注。
??系列專欄:vue3從入門到精通
??個(gè)人簽名:不破不立
一、Promise.all()簡介
Promise.all() 方法接收一個(gè) promise 的 iterable 類型(注:Array,Map,Set 都屬于 ES6 的 iterable 類型)的輸入,并且只返回一個(gè)Promise實(shí)例,并且輸入的所有 promise 的 resolve 回調(diào)的結(jié)果是一個(gè)數(shù)組。
- Promise的 resolve 回調(diào)執(zhí)行是在所有輸入的 promise 的 resolve 回調(diào)都結(jié)束,或者輸入的 iterable 里沒有 promise 了的時(shí)候
- Promise的 reject 回調(diào)執(zhí)行是只要任何一個(gè)輸入的 promise 的 reject 回調(diào)執(zhí)行或者輸入不合法的 promise 就會(huì)立即拋出錯(cuò)誤,并且只要有 reject 就會(huì)立即拋出的錯(cuò)誤信息。
二、async/await實(shí)現(xiàn)Promise.all()
先定義三個(gè)Promise實(shí)例對(duì)象,并放置于一個(gè)數(shù)組中
let a = new Promise((res, rej) => {
res(1)
}).catch(err => console.log(err))
let b = new Promise((res, rej) => {
setTimeout(() => {
rej(2)
}, 2000)
}).catch(err => console.log(err))
let c = new Promise((res, rej) => {
res(3)
}).catch(err => console.log(err))
const arr = [a, b, c]
1、方式一
-使用async/await,循環(huán)遍歷Promise實(shí)例對(duì)象的數(shù)組,并把每個(gè)Promise對(duì)象的結(jié)果放置于一個(gè)空數(shù)組中。
async function bb() {
let arr1 = [];
try {
for (let i = 0; i < arr.length; i++) {
let h = await arr[i]
arr1.push(h)
}
} catch (err) {
}
return arr1
}
bb().then(res => {
console.log(res); //[1, undefined, 3]
});
undefined
是因?yàn)閍wait只處理成功時(shí)resolve(),不處理失敗異常,故返回undefined
2、方式二
該方面類似實(shí)現(xiàn)手寫Promise.acll(),等await拿到Promise結(jié)果然后count加1,知道count的數(shù)值等于數(shù)值的長度在resolve()文章來源:http://www.zghlxwxcb.cn/news/detail-799792.html
const all = (arr) => {
return new Promise((resolve, reject) => {
let length = arr && arr.length
let count = 0
let result = []
if (!arr || arr.length === 0) {
resolve(result)
}
arr.forEach(async (item, index) => {
try {
const res = await item
result[index] = res
count++
if (count === length ) {
resolve(result)
}
} catch (err) {
reject(err)
}
});
})
}
三、async/await與Promise.all()結(jié)合使用
因?yàn)镻romise.all()返回的也是Promise,所以await 后面可以跟Promise.all()文章來源地址http://www.zghlxwxcb.cn/news/detail-799792.html
function fn() {
return new Promise((resolve, reject) => {
resolve(Math.random())
})
}
async function asyncFunc() {
let result
try {
result = await Promise.all([fn(), fn()])
console.log(result)
} catch (err) {
console.log(err, 'err')
}
return result
}
asyncFunc().then(res => { console.log(res, 'res') })
到了這里,關(guān)于async/await實(shí)現(xiàn)Promise.all()的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!