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 results; if every task must succeed, Promise.all() is still the better fit. The Problem Suppose a dashboard page calls three APIs at once with Promise.all(): const [user, posts, stats] = await Promise.all([ fetch("/api/user").then((r) => r.json()), fetch("/api/posts").then((r) => r.json()), fetch("/api/stats").then((r) => r.json()), ]); One 500 error from the stats API rejects the whole Promise.all() immediately. The other two APIs may have returned correct data, but it gets thrown away, the dashboard goes blank, and the user has to reload everything. The failure is even more annoying because the APIs have nothing to do with each other: the user data and the posts could easily show first, with only the stats block reporting an error. The Solution Promise.allSettled() waits for all promises to settle — fulfilled or rejected — then returns an array of results in the same order as the input. Each element has a status of “fulfilled” with a value, or “rejected” with a reason, so you filter out the successful ones to display and handle the failures separately: const results = await Promise.allSettled([ fetch("/api/user").then((r) => r.json()), fetch("/api/posts").then((r) => r.json()), fetch("/api/stats").then((r) => r.json()), ]); const [user, posts, stats] = results.map((r) => r.status === "fulfilled" ? r.value : null ); if (stats === null) { console.warn("Không tải được thống kê:", results[2].reason); } With this approach, the dashboard still shows the user info and the posts, and only the stats block shows an error message. You can also collect the errors for logging, or retry only the failed APIs instead of calling all three again. Apply It to Your Project Use Promise.allSettled() anywhere you call several independent tasks and want to keep partial results: a dashboard calling many APIs, an import job processing a batch of files, a status screen checking many services at once, or a feature sending email to many recipients where one bad address must not block the rest. The rule to remember: independent tasks → allSettled, tasks that must all succeed → Promise.all. Related Posts JavaScript: fetch() không tự timeout — hủy request treo bằng AbortController trong 5 phút Temporal “về đích”: JavaScript cuối cùng cũng có API xử lý ngày giờ chuẩn — dùng được ngay trên Chrome, Firefox và Node 26 Node.js 26.10.0 ra mắt: crypto.parsePKCS12(), fs.openAsBlobSync(), util.throttle()/debounce() và cải tiến SQLite FAQ How is Promise.allSettled() different from Promise.all()? Promise.all() stops as soon as one promise rejects and discards all results, while Promise.allSettled() waits for everything to finish and returns each task’s status, so you always get the data from the tasks that succeeded. Do the results keep the same order as the input promises? Yes. The result array is always ordered exactly like the promise array you passed in, no matter which promise finished first or last, so you can assign results by index as in the example above. When should I still use Promise.all() instead of Promise.allSettled()? When the steps depend on each other or all of them must succeed — creating an order before deducting stock, for example. Then one failing step has to stop the whole flow, and Promise.all()’s fail-fast behavior is the right one. Which browsers and Node.js versions support Promise.allSettled()? It’s an ES2020 feature, available in Chrome 76+, Firefox 71+, Safari 13+, and Node.js 12.9 and later. For very old browsers, add a polyfill or use a library like core-js. 💬 Have you tried this in your own project? If you hit an error or know a shorter way, leave a comment below — I read them all and will add the good ideas to the post. References MDN Web Docs — Promise.allSettled() MDN Web Docs — Using promises
This is a summary aggregated from Dev.to. Read the complete article on the original site:
Read full article at Dev.to