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

A developer who writes somethings useful.
Search for a command to run...
Promise Strategies in JavaScript

A developer who writes somethings useful.
No comments yet. Be the first to comment.
Welcome to the Crawl Budget Circus! 🎪 Step right up, ladies and gentlemen! Today, we’re diving into the thrilling world of crawl budgets—the magical limit that determines how much time Googlebot spends crawling your website. Think of it as a circus ...

A simple math trick discovered by Indian mathematician D. R. Kaprekar

Efficiency at Your Fingertips in Visual Studio Code

Tracing the Roots of the World Wide Web and HTML Evolution

Unlocking Unpopular Functions in JavaScript for Better Code

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.
Promise.race: The Fast and the FirstImagine 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.
Promise.allSettled: Handling Life's CurveballsNow, 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.
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! 🚀✨