Created
January 26, 2018 18:55
-
-
Save AkyunaAkish/7ab0b870994b84260f0ca0f567371756 to your computer and use it in GitHub Desktop.
Handling multiple function calls that each return a Promise using Promise.all
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 asyncFunction(bool) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if(bool) { | |
resolve('Promise resolved after 5 seconds'); | |
} else { | |
reject('Promise rejected after 5 seconds'); | |
} | |
}, 5000); | |
}); | |
} | |
const unresolvedPromises = []; | |
for(let i = 0; i < 5; i++) { | |
// push the function call to an array | |
// gathering an array of unfinished/unresolved Promises | |
unresolvedPromises.push(asyncFunction(true)); | |
} | |
// Promise.all will wait for each unresolved function | |
// to finish before passing an array of results to the | |
// .then | |
Promise.all(unresolvedPromises).then((result) => { | |
console.log('Handle resolved results here', result); | |
}) | |
.catch((err) => { | |
// if a promise rejects, the resolved values will be lost | |
// and you will only receive one error in the .catch | |
console.log('Handle rejected error here', err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment