# 题目描述
请你实现Promise.allSettled
一句话概括就是👇
等到传入Promise数组所有的的promise都执行完毕了,返回一个Promise,它的resolve中包含所有返回结果的对象数组
- 返回成功的对象就是
resolve: {status: "fulfilled", value: "xx"}
- 返回失败的对象就是
reject: {status: "rejected", reason: "xx"}
如果传入参数数组为空,就返回空数组
MDN
上的描述
Promise. allsettle()
静态方法接受Promise
的可迭代对象作为输入,并返回一个Promise
。当所有输入的promise
都完成时(包括传递空可迭代对象时),这个返回的promise
就会完成,并使用一个对象数组来描述每个promise的结果 —— resolve(resArr)
# 代码实现
const allSettled = function (promises) {
// 返回一个对象数组
// resolve: {status: "fulfilled", value: "xx"}
// reject: {status: "rejected", reason: "xx"}
let res = [];
if (promises.length === 0) {
return res;
}
return new Promise((resolve) => {
let len = promises.length;
promises.forEach((item, index) => {
Promise.resolve(item).then(
(value) => {
res[index] = {
status: "fulfilled",
value,
};
len--;
if (len === 0) {
resolve(res);
}
},
(reason) => {
res[index] = {
status: "rejected",
reason,
};
len--;
if (len === 0) {
resolve(res);
}
}
);
});
});
};
const p1 = new Promise((resolve) => {
setTimeout(() => {
resolve(2);
}, 3000);
});
const p2 = Promise.reject("error");
const p3 = new Promise((resolve) => {
setTimeout(() => {
resolve("5");
}, 1000);
});
const p4 = new Promise((resolve) => {
setTimeout(() => {
resolve("4");
}, 2000);
});
const p5 = 5;
allSettled([p1, p2, p3, p5]).then((res) => console.log("2: ", res));
/*
2: [
{ status: 'fulfilled', value: 2 },
{ status: 'rejected', reason: 'error' },
{ status: 'fulfilled', value: '5' },
{ status: 'fulfilled', value: 5 }
]
*/
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
57
58
59
60
61
62
63
64
65
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
57
58
59
60
61
62
63
64
65