-
Notifications
You must be signed in to change notification settings - Fork 0
/
any.js
55 lines (47 loc) · 1.61 KB
/
any.js
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
/*-----Polyfill for Promise.any function of JavaScript-----*/
// -----Explanation-----
// The Promise.any() method in JavaScript is a static method that takes an iterable (like an array) of promises as input and returns a single Promise.
// The returned promise from Promise.any() 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.
// -----Real Implementation-----
const pErr = new Promise((resolve, reject) => {
reject("Always fails");
});
const pSlow = new Promise((resolve, reject) => {
setTimeout(resolve, 100, "Done eventually");
});
const pFast = new Promise((resolve, reject) => {
setTimeout(resolve, 100, "Done quick");
});
Promise.any([pErr, pSlow, pFast]).then((value) => {
console.log(value);
});
//-----Polyfill-----
const myPromiseAny = function (promises) {
return new Promise((resolve, reject) => {
let count = promises.length;
const result = [];
if (count === 0) {
reject(new AggregateError("All promises were rejected"));
}
promises.forEach((promise, index) => {
Promise.resolve(promise)
.then((value) => resolve(value))
.catch((err) => {
result[index] = err;
count--;
if (count === 0) {
reject(new AggregateError(result));
}
});
});
});
};
//-----Polyfill Implementation-----
myPromiseAny([pErr])
.then((value) => {
console.log(value);
})
.catch((err) => {
console.log(err);
});