部分摘自MDN數組
咱們來看例子1promise
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promiseList = [promise1,promise2]
Promise.all(promiseList)
.then((values) => {
console.log(20, values) //會輸出3, 42
})
.catch(err => {
console.log(22, err)
})
複製代碼
例子2ui
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => reject('我是失敗的Promise_1'))
const promise4 = new Promise((resolve, reject) => reject('我是失敗的Promise_2'))
const promiseList = [promise1,promise2,promise3, promise4]
Promise.all(promiseList)
.then((values) => {
console.log(20, values) //不會走這裏的回調
})
.catch(err => {
console.log(22, err) //輸出 `我是失敗的Promise_1` 只會返回第一個reject而中斷
})
複製代碼
問題: 沒法準確的定位錯誤,因此就有了Promise.allSettledspa
例子3d
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => reject('我是失敗的Promise_1'))
const promise4 = new Promise((resolve, reject) => reject('我是失敗的Promise_2'))
const promiseList = [promise1,promise2,promise3, promise4]
Promise.allSettled(promiseList).then(values=>{
console.log(26, values)
})
複製代碼
輸出結果:code