All 28 lessons ▾
Inside JavaScript · Lesson 25 of 28
Promise APIs Part 1: Promise.all and Promise.allSettled
So, load three things at once, and wait for all of them, or take whatever works. Promise.all and allSettled make it easy. So let's master both.
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
- Promise APIs handle many promises at once
- Promise.all: all results, in input order
- It fails fast on the first rejection
- Promise.allSettled waits for every promise
- It never rejects: a status with a value or a reason
- all for all-or-nothing, allSettled for independent parts
Part 1Many promises at once
So in the last episode, we saw a trap. Awaiting independent tasks one by one wastes time, and the fix was Promise.all. So today, we go deep into the Promise APIs, the helper functions that handle many promises together. There are four big ones. all, allSettled, race, and any. In this episode, all and allSettled. And interviewers ask about these all the time.
1const details = new Promise((resolve) => {2 setTimeout(() => resolve("details"), 3000);3});4const showtimes = new Promise((resolve) => {5 setTimeout(() => resolve("showtimes"), 1000);6});7const reviews = new Promise((resolve) => {8 setTimeout(() => resolve("reviews"), 2000);9});So here's our setup for today. A movie page needs three things from the server. The movie details, which take three seconds. The showtimes, which take one second. And the reviews, which take two seconds. So we'll fake each one with a timer. Three promises, all started at the same moment. Now remember from episode twenty three, a promise's work starts when it's created, not when you wait for it. So how do we handle all three together?
Part 2Promise.all
So first, Promise.all. This is the one you'll use the most.
1Promise.all([details, showtimes, reviews])2 .then((results) => console.log(results));3 4// after 3 seconds:5// ["details", "showtimes", "reviews"]So Promise.all takes an array of promises, and returns one new promise. Strictly, it takes any iterable, but in real code, it's almost always an array. Now that promise waits for all of them to succeed. Showtimes finishes at one second, reviews at two, and details at three. So after three seconds, the longest one, Promise.all is fulfilled, with an array of all the results. Now notice the order. Details, showtimes, reviews. The same order as the array we passed in, not the order they finished. That's a detail interviewers love to ask about.
So here's the picture. Three promises go in. Promise.all waits for the slowest one, details, at three seconds. And now out comes one array, with every result in its original place. So the total time is the time of the slowest promise, not the sum of all three. Three seconds, instead of six.
1const showtimes = new Promise((resolve, reject) => {2 setTimeout(() => reject(new Error("Showtimes failed")), 1000);3});4 5Promise.all([details, showtimes, reviews])6 .then((results) => console.log(results))7 .catch((err) => console.log(err.message));8 9// after 1 second:10// Showtimes failedBut now what if one of them fails? Say the showtimes request fails, at one second. Promise.all doesn't wait for the others. The moment one promise rejects, Promise.all rejects too, immediately, with that same error. So after just one second, the catch prints, showtimes failed. This is called fail fast. And now notice, the other two requests are not cancelled. In fact, JavaScript has no way to cancel a promise once its work has started. Details and reviews still finish in the background, but Promise.all ignores their results. So it's all, or nothing.
So remember this. Promise.all waits for every promise to be fulfilled, and gives you all the results in an array, in the same order as the input. But if any one promise rejects, it rejects immediately, with the first error. So use it when you truly need every result, like a checkout page that needs the cart, the address, and the payment methods together.
1async function loadMoviePage() {2 try {3 const [info, times, reviews] = await Promise.all([4 getDetails(),5 getShowtimes(),6 getReviews(),7 ]);8 render(info, times, reviews);9 } catch (err) {10 showError("Couldn't load the page: " + err.message);11 }12}And now in real code, you'll mostly use Promise.all with await. Start all three requests inside Promise.all, and await it once. Because the results come back in the same order, you can unpack them straight into three variables, info, times, and reviews. And since Promise.all rejects if any request fails, one try and catch around it handles every failure. So three requests, one await, one catch.
1const ids = [101, 102, 103, 104, 105];2 3const users = await Promise.all(4 ids.map((id) =>5 fetch("/api/users/" + id).then((res) => res.json())6 )7);And here's a pattern you'll write all the time. So you have a list of user IDs, and you need every user. So map each ID to a fetch, and pass that whole array of promises to Promise.all. Five requests, all in parallel, and one await for all of them. Ten IDs, or a hundred, the code stays exactly the same.
1Promise.all([1, "two", Promise.resolve(3)])2 .then((r) => console.log(r)); // [1, "two", 3]3 4Promise.all([])5 .then((r) => console.log(r)); // [] right awayNow two small edge cases, because interviewers like them. First, you can mix plain values into the array. One, and the string two, aren't promises, so Promise.all treats them as already fulfilled, and passes them straight through. Second, an empty array. There's nothing to wait for, so Promise.all is fulfilled immediately, with an empty array.
Part 3Promise.allSettled
But sometimes, all or nothing is too strict. So what if you want whatever you can get?
1Promise.allSettled([details, showtimes, reviews])2 .then((results) => console.log(results));3 4// after 3 seconds:5// [6// { status: "fulfilled", value: "details" },7// { status: "rejected", reason: Error("Showtimes failed") },8// { status: "fulfilled", value: "reviews" }9// ]So that's Promise.allSettled. It waits for every promise to settle, whether it succeeds, or fails. Same three promises, and showtimes still fails at one second. But now allSettled keeps waiting. After three seconds, when all three are done, it gives you an array of objects. Each one has a status. Fulfilled, with a value. Or rejected, with a reason. So details and reviews are here, and showtimes tells you why it failed. Nothing is thrown away.
1async function loadPage() {2 const results = await Promise.allSettled([details, showtimes, reviews]);3 4 results.forEach((r) => {5 if (r.status === "fulfilled") {6 show(r.value);7 } else {8 showRetryButton();9 }10 });11}And now here's how you use it in a real app. Await allSettled, then loop through the results. So for each one that's fulfilled, show it on the page. For each one that's rejected, show a small retry button instead. So if only the showtimes fail, the user still sees the details and the reviews. The page doesn't break, just because one part failed. And users forgive a missing section much more easily than a blank screen.
So remember this. Promise.allSettled waits for all the promises to settle, and it never rejects. So it always gives you the full picture, with a status for each one. That's why many people call it the safest of the Promise APIs. So use it when each task is independent, like the widgets on a dashboard. Now it was added to JavaScript in ES2020, so every modern browser and Node version supports it.
Part 4all or allSettled?
So, which one should you use in your own code? It comes down to one simple question. Let's see.
So let's put them side by side. Promise.all fails fast. If you need everything to succeed, like a checkout, use all. Promise.allSettled waits for everyone, and reports each result. If the parts are independent, like a dashboard, use allSettled. So just ask yourself one question. If one part fails, should everything fail?
1function myAll(promises) {2 return new Promise((resolve, reject) => {3 const results = [];4 let done = 0;5 if (promises.length === 0) return resolve(results);6 promises.forEach((p, i) => {7 Promise.resolve(p)8 .then((value) => {9 results[i] = value;10 done++;11 if (done === promises.length) resolve(results);12 })13 .catch(reject);14 });15 });16}And now here's a favourite interview task. Write your own Promise.all. So let's go line by line. We return a new promise. Inside, an empty results array, and a counter called done. An empty input resolves straight away. Then, for every promise, we wrap it with Promise.resolve, so plain values work too. When one fulfills, we put its value at its own index, i. That's how the order is kept, even if they finish in a different order. We count it, and when done equals the total, we resolve with the results. And if any one rejects, we call reject. Fail fast. So that's the whole of Promise.all, in fifteen lines.
1const a = Promise.resolve(1);2const b = Promise.reject(new Error("2 failed"));3const c = Promise.resolve(3);4 5Promise.all([a, b, c])6 .then((r) => console.log("all:", r))7 .catch((e) => console.log("all failed:", e.message));8 9Promise.allSettled([a, b, c])10 .then((r) => console.log("settled:", r.length));What do the two calls print?
Show the answer
So Promise.all sees that b rejected, so it fails fast, and prints, all failed, two failed. Promise.allSettled waits for all three, and resolves with three status objects, so it prints, settled, three. So one gives up, the other reports everything. Did you get both?
Make five promises with different timers. Fail one, then fail them all, and predict what all and allSettled print, before you run it. Then tell me in the comments, where would you use allSettled in your own project?
Show the answer
Here's a helper that makes a promise with a timer, which succeeds or fails:
1const wait = (ms, name, fail) =>2 new Promise((resolve, reject) => {3 setTimeout(() => (fail ? reject(new Error(name + " failed")) : resolve(name)), ms);4 });5 6const five = [wait(300, "p1"), wait(100, "p2"), wait(500, "p3", true), wait(200, "p4"), wait(400, "p5")];7 8Promise.all(five)9 .then((r) => console.log("all:", r))10 .catch((e) => console.log("all failed:", e.message));11 12Promise.allSettled(five)13 .then((r) => console.log("settled:", r.map((x) => x.status)));With one failure (p3), all fails fast with all failed: p3 failed, and allSettled still reports all five: four fulfilled and one rejected.
Now make all five fail. all rejects with the first failure in time, not in the array: p2, at 100 ms, so all failed: p2 failed. allSettled still waits for all five, and reports five rejected. It never rejects.
Where would you use allSettled? Anywhere one failure shouldn't throw away the rest: a dashboard loading five widgets, sending a message to many people, uploading several photos. Show what worked, and retry what didn't.
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.