All 28 lessons ▾
Inside JavaScript · Lesson 26 of 28
Promise APIs Part 2: Promise.race, Promise.any and Interview Questions
So, the first one to finish wins. Or the first one to succeed. Promise.race and Promise.any, plus the interview questions that come with them.
A new lesson goes up every day at 11 am. Subscribe on YouTube so you don't miss it.
Got a doubt? Ask in the comments under the video.Subscribe
- race: the first to settle wins
- Use race for timeouts
- any: the first success wins
- All failed? AggregateError, with err.errors
- Settled means fulfilled or rejected
- Know when to use all, allSettled, race and any
Part 1Promise.race
So in part one, we learned Promise.all and allSettled, which wait for everything. So today, two APIs that care about who finishes first. race, and any. Now they sound similar, but they're different in one important way. And then, the interview questions that tie all four together.
1Promise.race([details, showtimes, reviews])2 .then((value) => console.log(value))3 .catch((err) => console.log(err.message));4 5// after 1 second:6// showtimesSo Promise.race is exactly what it sounds like. A race! It takes an array of promises, and settles as soon as the first one settles. Our three promises from last time. Details at three seconds, showtimes at one, and reviews at two. Showtimes finishes first, at one second. So race is fulfilled with showtimes. Just one value, not an array, because a race has only one winner. Now the other two still finish later, but race doesn't care. It already has its winner.
1const reviews = new Promise((resolve, reject) => {2 setTimeout(() => reject(new Error("Reviews failed")), 500);3});4 5Promise.race([details, showtimes, reviews])6 .then((value) => console.log(value))7 .catch((err) => console.log(err.message));8 9// after half a second:10// Reviews failedBut now here's the important part. race takes the first one to settle, success or failure. Now say reviews fails, after just half a second. That's the first promise to settle. So race rejects, with reviews failed, even though showtimes would have succeeded a moment later. So in a race, the first to finish wins, even if it finished by falling over. Funny.
1function timeout(ms) {2 return new Promise((resolve, reject) => {3 setTimeout(() => reject(new Error("Too slow!")), ms);4 });5}6 7Promise.race([fetch("/api/movies"), timeout(5000)])8 .then((response) => console.log("Got it in time"))9 .catch((err) => console.log(err.message));So where is race actually useful? The classic example is a timeout. fetch has no time limit by default. So we race it against a timer that rejects after five seconds. If the server answers first, we get the response. If five seconds pass first, the timer wins, and we get, too slow. So now no request can hang forever. That's race, used properly.
1Promise.race([2 Promise.all([getDetails(), getShowtimes(), getReviews()]),3 timeout(5000),4])5 .then(([info, times, reviews]) => render(info, times, reviews))6 .catch((err) => showError(err.message));And now you can combine them. Here, Promise.all loads the whole movie page, all three requests together. And we race that against the five second timeout. So the page either loads completely within five seconds, or the user sees a clear error, instead of a spinner that never ends. So real apps are built from exactly these small pieces.
So remember this. Promise.race settles with the first promise that settles. If that first one succeeded, race succeeds. If that first one failed, race fails. It doesn't wait for anything else. And its most common use is a timeout.
Part 2Promise.any
Now, its cousin. Promise.any. It's also looking for a winner, but it's pickier.
1const showtimes = new Promise((resolve, reject) => {2 setTimeout(() => reject(new Error("Showtimes failed")), 1000);3});4 5Promise.any([details, showtimes, reviews])6 .then((value) => console.log(value));7 8// after 2 seconds:9// reviewsSo Promise.any waits for the first promise to succeed. So failures are ignored, as long as someone succeeds. Here, showtimes fails at one second. any ignores it, and keeps waiting. Reviews succeeds at two seconds. That's the first success. So any is fulfilled with reviews. Now compare that with race, which would have stopped at the first failure.
1Promise.any([p1, p2, p3]) // all three reject2 .catch((err) => {3 console.log(err.name); // AggregateError4 console.log(err.errors); // [error1, error2, error3]5 });And now what if every promise fails? Then there's no winner. So Promise.any rejects with a special error, called AggregateError. It means, all promises were rejected. And it carries all the individual errors in an array, called errors. So you can see exactly why each one failed.
1Promise.any([2 fetch("https://in.example.com/status"),3 fetch("https://sg.example.com/status"),4 fetch("https://us.example.com/status"),5]).then((response) => console.log("A working server answered"));So where would you use any? When you have backups. Say the same data lives on three servers, in India, Singapore, and the US. So ask all three at once, and use whichever answers successfully first. Now if one server is down, no problem. any ignores the failure. Only if all three are down do you get the AggregateError.
So remember this. Promise.any waits for the first success, and ignores failures. If everything fails, it rejects with an AggregateError, holding all the errors. And the difference from race, in one line. race takes the first to settle. any takes the first to succeed.
Part 3All four, side by side
Now let's put all four together, because the classic interview question is, what's the difference between them?
So Promise.all waits for everything to succeed, and fails fast on the first error. Promise.allSettled waits for everything to settle, and never rejects. Promise.race takes the first promise to settle, success or failure. And Promise.any takes the first success, with an AggregateError if there's none. So together with Promise.resolve and Promise.reject, that's all six static methods of Promise.
And now one word that confuses people. Settled. A promise is settled when it's done, either way. Fulfilled, or rejected. So when someone says resolved, success, or fulfilled, they mean the good case. And rejected, or failure, mean the bad case. Settled covers both. Now interviewers love to mix these words up, just to see if you're sure. So say them out loud a few times. Get these words right, and the four APIs become easy to remember. allSettled waits for all to settle. any waits for one to be fulfilled.
1function myRace(promises) {2 return new Promise((resolve, reject) => {3 promises.forEach((p) => {4 Promise.resolve(p).then(resolve, reject);5 });6 });7}And now here's a beautiful interview task. Write your own Promise.race. It's tiny! Return a new promise. For each input, attach resolve and reject directly. Whichever promise settles first calls resolve or reject, and the race is decided. But what about the slower ones? They call resolve or reject too, later. So why doesn't that break anything? Remember from episode twenty two. A promise settles only once! Every later call is simply ignored. So that one rule makes race possible, in five lines.
1function myAllSettled(promises) {2 return Promise.all(3 promises.map((p) =>4 Promise.resolve(p)5 .then((value) => ({ status: "fulfilled", value }))6 .catch((reason) => ({ status: "rejected", reason }))7 )8 );9}And now a harder one, write your own allSettled, using only Promise.all. So here's the trick. Promise.all fails fast, so we make sure nothing inside it can fail. We map every promise to a new one. If it fulfills, we turn the value into an object, status fulfilled, with the value. If it rejects, catch turns the error into an object too, status rejected, with the reason. Now every promise in the array succeeds, so Promise.all waits for all of them, and gives us the full report. So that's allSettled.
1Promise.race([]) // pending forever: nothing can win2 3Promise.any([]) // rejects at once: AggregateError4 5Promise.all([]) // fulfills at once: []And three quick edge cases, with empty arrays. Promise.race with an empty array stays pending forever, because there's no one to win the race. Now Promise.any with an empty array rejects at once, with an AggregateError, because no one can succeed. And as we saw last time, Promise.all with an empty array fulfills at once, with an empty array. So interviewers love these, because they show you understand the rules, not just the examples.
1const fast = new Promise((resolve, reject) => {2 setTimeout(() => reject(new Error("fast failed")), 100);3});4const slow = new Promise((resolve) => {5 setTimeout(() => resolve("slow worked"), 500);6});7 8Promise.race([fast, slow]).catch((e) => console.log("race:", e.message));9Promise.any([fast, slow]).then((v) => console.log("any:", v));What do race and any print?
Show the answer
So fast fails at one hundred milliseconds. slow succeeds at five hundred. race picks whichever settles first. That's fast, which failed. So race prints, race, fast failed. any ignores failures, and waits for the first success. That's slow. So any prints, any, slow worked. Same two promises, two different answers. Did you get both?
Take the quiz code, and change the timers. Make every promise fail, then make them all succeed, and predict what each API prints before you run it. Then tell me in the comments, which of the four will you use the most?
Show the answer
Every promise fails:
1const fast = new Promise((resolve, reject) => {2 setTimeout(() => reject(new Error("fast failed")), 100);3});4const slow = new Promise((resolve, reject) => {5 setTimeout(() => reject(new Error("slow failed")), 500);6});7 8Promise.race([fast, slow]).catch((e) => console.log("race:", e.message));9Promise.any([fast, slow]).catch((e) => console.log("any:", e.errors.length, "errors"));race settles with the first promise to settle, so at 100 ms it prints race: fast failed. any waits for a success that never comes, so at 500 ms it rejects with an AggregateError, and prints any: 2 errors.
Now make both succeed, with the values "fast worked" and "slow worked". race gives fast worked, the first to settle. any gives fast worked too, the first success.
And the other two, for the full picture:
all: both succeed,["fast worked", "slow worked"], in input order, at 500 ms. Both fail, it rejects withfast failedat 100 ms.allSettled: always waits for both, and resolves with two status objects. It never rejects.
Try it first, then post yours in the comments under the video.
The video on YouTube, and the lesson as a swipe-through on Instagram.