Discover how to handle many tasks at once without messy code or missed results!
Why Promise.race and Promise.allSettled in Node.js? - Purpose & Use Cases
Imagine you have several tasks running at the same time, like downloading files or fetching data from different websites, and you want to know when the first one finishes or when all of them have completed, no matter if they succeed or fail.
Manually tracking each task's completion is tricky and messy. You have to write lots of code to check each task's status, handle errors separately, and decide when to move on. This can easily lead to bugs and slow down your program.
Promise.race and Promise.allSettled let you handle multiple tasks easily. Promise.race gives you the result of the first task that finishes, while Promise.allSettled waits for all tasks to finish and tells you their outcomes, whether success or failure.
let finished = false;
tasks.forEach(task => {
task.then(result => {
if (!finished) {
finished = true;
console.log('First done:', result);
}
}).catch(() => {});
});Promise.race(tasks).then(result => console.log('First done:', result));You can easily manage many asynchronous tasks and react quickly to the first result or wait for all results without complicated code.
When loading images on a webpage, you might want to show the first image that loads quickly (Promise.race) or wait until all images have either loaded or failed before showing a gallery (Promise.allSettled).
Manually tracking multiple async tasks is complex and error-prone.
Promise.race returns the first finished task's result automatically.
Promise.allSettled waits for all tasks and reports their success or failure.