Promise.allSettled()
方法返回一个在所有给定的 promise 都已经fulfilled
或rejected
后的 promise,并带有一个对象数组,每个对象表示对应的 promise 结果
[ {status: 'fulfilled', value: 3}, {status: 'rejected', reason: 'foo'}]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| function myPromiseAllSelected(promises) { return new Promise((resolve, reject) => { let res = []; let iteratorIndex = 0; let fullCount = 0; for (let item of promises) { let resIndex = iteratorIndex; iteratorIndex++; Promise.resolve(item).then(value => { res[resIndex] = { status: 'fulfilled', value, }; fullCount++; if (fullCount === iteratorIndex) { resolve(res); } }).catch(reason => { res[resIndex] = { status: 'rejected', reason, }; fullCount++; if (fullCount === iteratorIndex) { resolve(res); } }) }; }) };
let p1 = Promise.resolve(3); let p2 = Promise.reject(2);
Promise.allSettled([p1, p2]).then(val => { console.log(val) }). catch(err => { console.log(err) });
myPromiseAllSelected([p1,p2]).then(res => console.log(res), err => console.log(err))
|