-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path5.1-promise-all.js
48 lines (39 loc) · 1.05 KB
/
5.1-promise-all.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
/*
Implement your own version of Promise.
all() leveraging promises, async/await, or a combination of the two.
The function must be functionally equivalent to its original counterpart.
*/
// 1. Promise.all using async await
async function promiseAll(promises) {
try {
for (const promise of promises) {
await promise;
}
} catch (e) {
console.log('Error in promiseAll', e);
}
}
// 2. Promise.all using promises
async function promiseAll2(promises) {
return new Promise((resolve, reject) => {
let resolvedPromises = 0;
promises.forEach((promise) => {
promise.then(() => {
resolvedPromises++;
if (resolvedPromises === promises.length) resolve();
}, reject);
})
});
}
// testing
function wait(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`Resolved ${ms}`);
resolve('Resolved successfully');
}, ms);
});
}
promiseAll2([wait(150), wait(399), wait(1500), wait(400), wait(5000), wait(5000)]).then(() => {
console.log('ALL promises are resolved');
})