Promise.allSettled()、Promise.any() polyfill

The Promise.allSettled() static method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the input’s promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise.

Promise.allSettled()
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
Promise.allSettled =
Promise.allSettled ||
function (arr) {
var P = this;
return new P(function (resolve, reject) {
if (Object.prototype.toString.call(arr) !== "[object Array]") {
return reject(
new TypeError(
typeof arr +
" " +
arr +
" " +
" is not iterable(cannot read property Symbol(Symbol.iterator))"
)
);
}
var args = Array.prototype.slice.call(arr);
if (args.length === 0) return resolve([]);
var arrCount = args.length;

function resolvePromise(index, value) {
if (typeof value === "object") {
var then = value.then;
if (typeof then === "function") {
then.call(
value,
function (val) {
args[index] = { status: "fulfilled", value: val };
if (--arrCount === 0) {
resolve(args);
}
},
function (e) {
args[index] = { status: "rejected", reason: e };
if (--arrCount === 0) {
resolve(args);
}
}
);
}
}
}

for (var i = 0; i < args.length; i++) {
resolvePromise(i, args[i]);
}
});
};

The Promise.any() static method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when any of the input’s promises fulfills, with this first fulfillment value. It rejects when all of the input’s promises reject (including when an empty iterable is passed), with an AggregateError containing an array of rejection reasons.

Promise.any()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Promise.any =
Promise.any ||
function any(promises) {
return Promise.all(
promises.map((promise) =>
promise.then(
(val) => {
throw val;
},
(reason) => reason
)
)
).then(
(reasons) => {
throw reasons;
},
(firstResolved) => firstResolved
);
};

Promise.allSettled()、Promise.any() polyfill

https://cn.thelynan.com/promise-all-settled-and-any/

作者

Lynan

发布于

2020-11-29

许可协议