Created
May 4, 2022 05:44
-
-
Save yitonghe00/04dbd4795f4118e13bbbb7c2c8a9bce5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Promise_all(promises) { | |
return new Promise((resolve, reject) => { | |
const array = []; | |
const promiseHelper = (promises) => { | |
if (promises.length === 0) { | |
resolve(array); // return array; | |
} | |
promises[0] | |
.then((value) => { | |
array.push(value); | |
promiseHelper(promises.slice(1)); | |
}) | |
.catch(reject); | |
}; | |
promiseHelper(promises); | |
}); | |
} | |
// 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); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment