Promise.allSettled方法

Promise.allSettled()方法返回一个在所有给定的promise已被决议或被拒绝后决议的promise,并带有一个对象数组,每个对象表示对应的promise结果。
allSettled函数是没有失败的(即使某个promise失败)

示例说明

1
2
3
4
5
6
7
8
var resolved = Promise.resolve(42);
var rejected = Promise.reject(-1);

Promise.allSettled([resolved, rejected]).then(function (results) {
assert.deepEqual(results, [
{ status: 'fulfilled', value: 42 },
{ status: 'rejected', reason: -1 }
]);

实现

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

Promise.allSettled = function(promiseArr){
let results = [];
let count=0;
return new Promise((resolve,reject)=>{
for(let i=0;i<promiseArr.length;i++){
var curr = promiseArr[i];
if(curr instanceof Promise){
curr.then(res=>{
results[i] = {
status:'fulfilled',
value : res
}
count++;
if(count >= promiseArr.length){
resolve(results);
}
},err=>{
results[i] = {
status : 'rejected',
reason : err
}
count++;
if(count >= promiseArr.length){
resolve(results);
}
})
} else {
results[i] = {
status : 'fulfilled',
value : curr
}
count++;
if(count >= promiseArr.length){
resolve(results);
}
}
}
});
}