-
Notifications
You must be signed in to change notification settings - Fork 61
/
PromiseRace-Polyfill.js
63 lines (55 loc) · 1.54 KB
/
PromiseRace-Polyfill.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
56
57
58
59
60
61
62
63
/* 💡"JavaScript-with-JC"
👉 Promise.race() and Its Polyfill
Promise.race() - It executes all passed promises concurrently and returns the first resolved or rejected promise result.
💡Promise.race() Case :-
1) If passed empty [], forever pending.
*/
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("1st Promise resolved!");
}, 1000);
});
const p2 = Promise.reject("2nd Promise rejected!");
const p3 = 3;
const p4 = new Promise((resolve, reject) => {
setTimeout(() => {
let status = true;
if (status) {
resolve("4th Promise resolved!");
} else {
reject("4th Promise rejected!");
}
}, 2000);
});
Promise.race([p1, p2, p3, p4])
.then((result) => {
console.log("result race", result); // 2nd Promise rejected!
})
.catch((error) => {
console.log("error race", error);
});
//💡 Polyfill of Promise.race
Promise.customRace = function (promisesArray) {
// 👇 return a new promise
return new Promise((resolve, reject) => {
// 👇 execute each promise of promisesArray
for (let i = 0; i < promisesArray.length; i++) {
Promise.resolve(promisesArray[i]).then(
// 👇 return first resolved or rejected promise
(response) => {
resolve(response);
},
(error) => {
reject(error);
}
);
}
});
};
Promise.customRace([p1, p2, p3, p4])
.then((result) => {
console.log("result customRace", result); // 2nd Promise rejected!
})
.catch((error) => {
console.log("error customRace", error);
});