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.
As other answers mentioned, Promises are a good way to go. Promise.all() was mentioned in one but that one returns and rejects immediately if one of the promises fails.
Promise.allSettled() is a good option if you want it to return only when ALL the promises are completed. This allows for handling if some promises were fulfilled while others were rejected.
Here's a sample from the Mozilla docs:
Promise.allSettled([
Promise.resolve(33),
new Promise(resolve => setTimeout(() => resolve(66), 0)),
99,
Promise.reject(new Error('an error'))
])
.then(values => console.log(values));
// [
// {status: "fulfilled", value: 33},
// {status: "fulfilled", value: 66},
// {status: "fulfilled", value: 99},
// {status: "rejected", reason: Error: an error}
// ]