JavaScript: Run Multiple Promises at Once with Promise.allSettled — One Failure Won't Ruin the Batch
When you need to call several independent APIs at once — fetching user info, the post list, and statistics for a dashboard page, for example — Promise.allSettled() is the right choice. It waits for every promise to finish, then returns each one’s result, so one failing API doesn’t throw away the data from the rest. Only use it when the tasks are independent of each other and you accept partial…
Promise.allSettled() is a JavaScript method that allows developers to run multiple promises concurrently without any of them being able to ruin the entire batch of results. This is particularly useful when dealing with independent API calls, such as fetching user information, post lists, and statistics for a dashboard page.
When using Promise.allSettled(), the method waits for every promise to complete, regardless of whether they were successful or not. It then returns an array containing the results of each promise in the same order as the input. Each result includes a status ("fulfilled" or "rejected") and either a value or a reason for the rejection.
For example, suppose a dashboard page needs to call three separate APIs at once: one for user data, one for post lists, and one for statistics. Traditionally, using Promise.all() would cause the entire batch to fail if even one API returned a 500 error. However, with Promise.allSettled(), the method waits for all three promises to settle (either by fulfilling or rejecting). It then returns an array of results that includes both successful and failed promise outcomes.
By mapping over the results array, developers can filter out the successful data and handle any failures separately. In the case of a failed stats API call, the dashboard can display the user and post data while showing an error message for the stats section. Additionally, developers can collect the error reasons for logging, retry only the failed API calls, or take other appropriate actions.
It's important to note that Promise.allSettled() should only be used when the individual tasks are independent of each other and partial results are acceptable. If every task must succeed, Promise.all() is the better choice. Promise.allSettled() is an ES2020 feature supported in modern browsers (Chrome 76+, Firefox 71+, Safari 13+) and Node.js 12.9 and later. For older browsers, developers can use a polyfill or a library like core-js.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.