-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromiseall.js
67 lines (59 loc) · 1.92 KB
/
promiseall.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
64
65
66
67
// NOTE: Any valid solution (even using Promise.all) would fail test case 27
// with a 'Time Limit Exceeded' error. This is a bug.
// TODO: Submit again when they fix this bug.
// then/catch
function promiseAll(functions) {
return new Promise((resolve, reject) => {
const results = [];
const total = functions.length;
let completed = 0;
functions.forEach((func, i) => {
func()
.then((result) => {
results[i] = result;
completed++;
if (completed === total) {
resolve(results);
}
})
.catch((error) => {
reject(error);
});
});
});
}
// async/await
async function promiseAll2(functions) {
return new Promise((resolve, reject) => {
const results = [];
const total = functions.length;
let completed = 0;
try {
functions.forEach(async (func, i) => {
results[i] = await func();
completed++;
if (completed === total) {
resolve(results);
}
});
} catch (error) {
reject(error);
}
});
}
const promise = promiseAll([() => new Promise((res) => res(42))]);
promise.then(console.log); // [42]
// Test case 27
const promise2 = promiseAll2([
() => new Promise((resolve) => setTimeout(() => resolve(1), 100)),
() => new Promise((resolve) => setTimeout(() => resolve(2), 80)),
() => new Promise((resolve) => setTimeout(() => resolve(3), 50)),
() => new Promise((resolve) => setTimeout(() => resolve(4), 20)),
() => new Promise((resolve) => setTimeout(() => resolve(5), 280)),
() => new Promise((resolve) => setTimeout(() => resolve(6), 250)),
() => new Promise((resolve) => setTimeout(() => resolve(7), 220)),
() => new Promise((resolve) => setTimeout(() => resolve(8), 130)),
() => new Promise((resolve) => setTimeout(() => resolve(9), 160)),
() => new Promise((resolve) => setTimeout(() => resolve(10), 190)),
]);
promise2.then(console.log);