Index
[JavaScript] Handling multiple promises
When you have multiple promises you want to run in parallel, you can use Promise.all() or Promise.allSettled() to process them. See the comments and the note below for the key difference.
const promise1 = getPromise1();const promise2 = getPromise2();
// `resultsAll` will be an array of the resolved values of promise1 and promise2.const resultsAll = await Promise.all([promise1, promise2]);
// `resultsAllSettled` will be an array of objects that describe the result of each promise,// including a `status` of 'fulfilled' or 'rejected', and a `value` or `reason`.const resultsAllSettled = await Promise.allSettled([promise1, promise2]);Here is an example of using Promise.allSettled() and collecting up the errors:
const promises = [promise1, promise2];const results = await Promise.allSettled(promises);const errors = results.filter(result => result.status === 'rejected');Iterate over a list of items and run promises in parallel or serial
Sometimes you’ll have a list of items, and you want to run a promise for each item in parallel. For example, a list of IDs that you want to fetch data for from an API. You could map the items into promises first and then use Promise.all() to run them all in parallel.
const ids = [1, 2, 3, 4, 5];const promises = ids.map(id => getData(id));const results = await Promise.all(promises);To process these promise in serial (i.e. guaranteed one by one), you can use for...of to iterate over the items and run the promises:
const ids = [1, 2, 3, 4, 5];for (const id of ids) { await getData(id);}