Demystifying JavaScript Promises: A Tale of Promise.race and Promise.allSettled

Promise Strategies in JavaScript

ยท

2 min read

Demystifying JavaScript Promises: A Tale of Promise.race and Promise.allSettled

Let's talk about two cool JavaScript tools: Promise.race and Promise.allSettled. Think of them as your trusty superheroes for dealing with multiple promises.

Meet Promise.race: The Fast and the First

Imagine you're in a race with a bunch of tasks, each taking a different amount of time to finish. Some are sprinters, while others are marathon runners. Now, enter Promise.race - the race coordinator of JavaScript promises!

const task1 = new Promise(resolve => setTimeout(() => resolve('Task 1 completed'), 2000));
const task2 = new Promise(resolve => setTimeout(() => resolve('Task 2 completed'), 1500));
const task3 = new Promise(resolve => setTimeout(() => resolve('Task 3 completed'), 1000));

const winnerTask = Promise.race([task1, task2, task3]);

winnerTask.then(result => console.log(result));
// Output: "Task 3 completed" (Task 3 finishes first)

In this scenario, Promise.race is like the referee, and it shouts out the winner as soon as the first task crosses the finish line. It's a great way to handle tasks when you're only interested in the fastest result.

Enter Promise.allSettled: Handling Life's Curveballs

Now, picture this: you're juggling multiple promises, perhaps making requests to different corners of the internet. Some requests may succeed, while others hit roadblocks. That's where Promise.allSettled comes to the rescue!

const userIds = [101, 102, 103];
const apiUrl = 'https://api.example.com/users/';

const fetchUser = (userId) => {
  const url = `${apiUrl}${userId}`;
  return fetch(url)
    .then(response => response.json())
    .then(user => ({ status: 'fulfilled', value: user }))
    .catch(error => ({ status: 'rejected', reason: error }));
};

const fetchUserPromises = userIds.map(fetchUser);

const handleUserResults = (results) => {
  results.forEach(result => {
    if (result.status === 'fulfilled') {
      console.log('User Data:', result.value);
    } else {
      console.error('Error fetching user:', result.reason.message);
    }
  });
};

const allUserPromises = Promise.allSettled(fetchUserPromises);

allUserPromises.then(handleUserResults);

Think of Promise.allSettled as your reliable friend who collects reports on each promise, whether they succeed or face challenges. It's perfect for scenarios where you want to know the outcome of every promise, no matter what life throws at them.

Wrapping Up

And that's a quick peek into the worlds of Promise.race and Promise.allSettled. These superheroes might not have capes, but they're your go-to allies when dealing with multiple promises in JavaScript.

Happy coding, and may your promises always resolve! ๐Ÿš€โœจ

ย