Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yitonghe00/04dbd4795f4118e13bbbb7c2c8a9bce5 to your computer and use it in GitHub Desktop.
Save yitonghe00/04dbd4795f4118e13bbbb7c2c8a9bce5 to your computer and use it in GitHub Desktop.
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