I have a function foo which makes multiple (parallel) asynchronous calls in a loop. I need to somehow wait until the results of all of the calls are available.
Don't use Promise.all! That fails the entire operation if any one of your promises fails!
Unless you're okay with that prospect, you'd be way better off doing something like this:
function sleep(ms) {
return new Promise((resolve, reject) => {
console.log(`starting ${ms}`);
setTimeout(() => {
if (ms > 1000) {
console.log(`Threw out ${ms} because it took too long!`);
reject(ms);
} else {
console.log(`done ${ms}`);
resolve(ms);
}
}, ms);
});
}
(async () => {
console.log('aPromise, bPromise, cPromise executed concurrently as promises are in an array');
const start = new Date();
const aPromise = sleep(2000);
const bPromise = sleep(500);
const cPromise = sleep(5);
try {
const [a, b, c] = [await aPromise, await bPromise, await cPromise];
// The code below this line will only run when all 3 promises are fulfilled:
console.log(`slept well - got ${a} ${b} ${c} in ${new Date()-start}ms`);
} catch (err) {
console.log(`slept rough in ${err}ms`);
}
})();