forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path11_2_building_promiseall.js
More file actions
34 lines (33 loc) · 929 Bytes
/
11_2_building_promiseall.js
File metadata and controls
34 lines (33 loc) · 929 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
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);
}
});