Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 156 Β· Asynchronous JavaScript

Promise.all, allSettled, race and any

Run many async tasks at once with Promise.all, Promise.allSettled, Promise.race and Promise.any, and learn which combinator fits each job.

Real programs rarely wait for just one thing. A dashboard loads a profile, notifications and statistics. An image gallery loads twenty thumbnails. A search box asks two servers and uses whichever answers first. In each case you hold several promises and need one answer about them.

JavaScript has four built-in tools for this, called promise combinators: Promise.all(), Promise.allSettled(), Promise.race() and Promise.any(). Each takes a list of promises and returns a single new promise, but they differ in when that promise settles and what it contains. Picking the right one is mostly about answering one question: what should happen when something fails?

All the examples use a small helper that settles after a delay, so you can watch the timing. It stands in for real work such as a network request.

A helper for the examples

JavaScript
// Fulfills with `value` after `ms` milliseconds
function succeed(ms, value) {
  return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}

// Rejects with an Error after `ms` milliseconds
function fail(ms, message) {
  return new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
}

Each TryIt below repeats these two functions so it can run on its own.

Promise.all(): everything must succeed

Promise.all(promises) fulfills when every promise has fulfilled. Its value is an array of the results, in the same order as the input, no matter which task finished first. If any promise rejects, the combined promise rejects immediately with that first error.

JS Promise.all collects results in order

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice two things. The results come back in input order even though the posts finished first. And the failing example rejects after about 100 ms, without waiting for the other two.

Use Promise.all() when the tasks belong together and a partial result is useless: you can't render a checkout page without both the cart and the prices.

Rejecting doesn't cancel anything. When Promise.all() rejects early, the other tasks keep running in the background; their results are simply ignored. Promises have no built-in cancellation. To actually stop work such as a fetch, use an AbortController.

The input doesn't have to contain only promises. Plain values are treated as already-fulfilled promises, so Promise.all([1, succeed(100, 2)]) gives [1, 2]. An empty array fulfills immediately with [].

Promise.allSettled(): wait for everything, then report

Sometimes one failure shouldn't spoil the rest. If a news page loads five widgets and the weather widget fails, you still want the other four. Promise.allSettled() never rejects. It waits until every promise has settled and gives you an array of result objects:

  • { status: "fulfilled", value: ... } for a success
  • { status: "rejected", reason: ... } for a failure
JS Promise.allSettled reports every outcome

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Use allSettled() for independent tasks where you want a full report: batch uploads, saving several records, health checks. It's also the safe choice whenever you would otherwise write Promise.all() and catch each promise individually.

Promise.race(): the first to settle wins

Promise.race() settles as soon as the first promise settles, whether it fulfills or rejects. The others are ignored.

The classic use is a timeout: race the real task against a promise that rejects after a few seconds. Whichever settles first decides the outcome.

JS A timeout with Promise.race

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Remember that "losing" the race doesn't stop the slow task; it still finishes in the background. For network requests, the modern way to time out and cancel is AbortSignal.timeout(), covered in Cancelling with AbortController.

An empty race never settles. Promise.race([]) stays pending forever. If your list of promises might be empty, check its length first.

Promise.any(): the first success wins

Promise.any() fulfills with the first promise to fulfill and ignores rejections, as long as at least one task succeeds. Only if every promise rejects does it reject, with an AggregateError whose errors property holds all the individual reasons.

That makes it ideal for redundancy: ask several mirrors or servers for the same data and take whichever responds successfully first.

JS Promise.any and AggregateError

Press Run (or Ctrl + Enter) to see the console output here.

No output.

race() and any() look alike but behave very differently in the first example. With race(), mirror A's quick failure would have won and rejected everything. any() skips past it.

Choosing a combinator

Combinator Fulfills when… Rejects when… Result
Promise.all() all fulfill the first one rejects array of values, input order
Promise.allSettled() all settle (either way) never array of { status, value / reason }
Promise.race() the first to settle fulfills the first to settle rejects that one value or reason
Promise.any() the first one fulfills all reject value, or AggregateError

A quick way to decide:

  • "I need all of them." β†’ Promise.all()
  • "I want all of them, but failures are OK." β†’ Promise.allSettled()
  • "Whatever happens first, success or failure." β†’ Promise.race()
  • "The first one that works." β†’ Promise.any()

All four are well supported. Promise.all() and Promise.race() arrived with promises in ES2015; allSettled() came in ES2020 and any() in ES2021, so every current browser and Node.js version has them.

Patterns and pitfalls

Create the promises, then combine them. Calling Promise.all([taskA(), taskB()]) starts both tasks right away. Writing await taskA() before building the array would run them one after the other, which is the sequential trap described in async and await.

Mapping over data. The most common real-world shape is turning an array of inputs into an array of promises:

JavaScript
const ids = [3, 8, 15];
const users = await Promise.all(ids.map((id) => loadUser(id)));

Too many at once. Promise.all() starts everything simultaneously. With hundreds of items that can overload a server or hit rate limits. A simple fix is to process the list in chunks:

JS Processing a list in batches

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Each batch runs in parallel, but no more than three requests are ever in flight. Libraries offer smarter "concurrency pools", but this simple version covers many cases.

Keep error information. With allSettled(), the reason is whatever was rejected. If you reject with real Error objects, as in these examples, you always get a message and a stack trace to work with.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. You need a user's profile AND their settings to render a page; without either, the page is useless. Which combinator fits?

    Promise.all() succeeds only when every task succeeds and fails fast as soon as one fails, which matches tasks that only make sense together.
  2. 2. What does Promise.allSettled() do when one of its promises rejects?

    allSettled() never rejects. Every input gets a result object describing how it settled.
  3. 3. Promise.race([fail(100), succeed(300)]) β€” what happens?

    race() follows whichever promise settles first, and here that is the rejection at 100 ms.
  4. 4. Every promise passed to Promise.any() rejects. What do you get?

    any() only rejects when all inputs reject, and it bundles their reasons into an AggregateError.
  5. 5. Promise.all() rejects because one of five requests failed. What happens to the other four?

    Promises have no built-in cancellation. To stop a request, pass it an AbortSignal and abort it.

Summary

  • Combinators turn many promises into one: all, allSettled, race and any.
  • Promise.all() gives an ordered array of values and rejects on the first failure.
  • Promise.allSettled() never rejects and reports each outcome as { status, value } or { status, reason }.
  • Promise.race() settles with the first promise to settle, success or failure; it's the classic timeout tool.
  • Promise.any() takes the first success and rejects with an AggregateError only if all fail.
  • Losing promises keep running; use AbortController to cancel real work, and batch large lists.

Next: Fetching Data with fetch() β€” make HTTP requests, read JSON and handle errors.