0
0
Node.jsframework~3 mins

Why Promise.race and Promise.allSettled in Node.js? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to handle many tasks at once without messy code or missed results!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
let finished = false;
tasks.forEach(task => {
  task.then(result => {
    if (!finished) {
      finished = true;
      console.log('First done:', result);
    }
  }).catch(() => {});
});
After
Promise.race(tasks).then(result => console.log('First done:', result));
What It Enables

You can easily manage many asynchronous tasks and react quickly to the first result or wait for all results without complicated code.

Real Life Example

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).

Key Takeaways

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.