-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbuilding_promise.all.js
More file actions
38 lines (37 loc) · 924 Bytes
/
building_promise.all.js
File metadata and controls
38 lines (37 loc) · 924 Bytes
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
function Promise_all(promises) {
return new Promise((resolve, reject) => {
let results = [];
let pending = promises.length;
for (let i = 0; i < promises.length; i++) {
promises[i]
.then((result) => {
results[i] = result;
pending--;
if (pending == 0) resolve(results);
})
.catch(reject);
}
if (promises.length == 0) resolve(results);
});
}
// Test code.
Promise_all([]).then((array) => {
console.log('This should be []:', array);
});
function soon(val) {
return new Promise((resolve) => {
setTimeout(() => resolve(val), Math.random() * 500);
});
}
Promise_all([soon(1), soon(2), soon(3)]).then((array) => {
console.log('This should be [1, 2, 3]:', array);
});
Promise_all([soon(1), Promise.reject('X'), soon(3)])
.then((array) => {
console.log('We should not get here');
})
.catch((error) => {
if (error != 'X') {
console.log('Unexpected failure:', error);
}
});