Skip to content

Instantly share code, notes, and snippets.

@frankchang0125
Last active June 26, 2017 09:19
Show Gist options
  • Save frankchang0125/72cce337558edfdb85e89208f77e5064 to your computer and use it in GitHub Desktop.
Save frankchang0125/72cce337558edfdb85e89208f77e5064 to your computer and use it in GitHub Desktop.
Wait for all promises to completed, even rejected promises.
const first = new Promise((resolve, reject) => {
setTimeout(() => resolve("first"), 1000);
});
const second = new Promise((resolve, reject) => {
setTimeout(() => reject("second error"), 2000);
});
const third = new Promise((resolve, reject) => {
setTimeout(() => resolve("third"), 3000);
});
const fourth = new Promise((resolve, reject) => {
setTimeout(() => reject("fourth error"), 4000);
});
const fifth = new Promise((resolve, reject) => {
setTimeout(() => resolve("fifth"), 5000);
});
/* By default, when any of the promises is rejected,
* Promise.all() will return error immediately without waiting for other unfinished promises.
*
* With following approach, we can wait for all promises to completed, even rejected promises.
* We achieve this by turning the rejected promises into the resolved ones with map() before passing promises to Promise.all().
* Therefore, all promises will be resolved and we can wait for them to completed.
*
* Output:
* Catched error: second error
* Catched error: fourth error
* Results:
* [ 'first', 'second error', 'third', 'fourth error', 'fifth' ]
*/
Promise.all([first, second, third, fourth, fifth].map(p => {
return p.catch(e => {
console.log("Catched error: " + e);
return e;
});
}))
.then(results => {
console.log("Results:");
console.log(results);
})
.catch(e => {
console.log("Error: " + e); // Never executed, just keep it as good practice.
});
@frankchang0125
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment