Last active
June 26, 2017 09:19
-
-
Save frankchang0125/72cce337558edfdb85e89208f77e5064 to your computer and use it in GitHub Desktop.
Wait for all promises to completed, even rejected promises.
This file contains hidden or 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
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. | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackoverflow.com/questions/31424561/wait-until-all-es6-promises-complete-even-rejected-promises