Skip to content
jshacks.dev
Async

Promise.all: Run in Parallel, Fail Fast

Learn how Promise.all runs promises together, returns results in input order and rejects on the first failure, with the cases where it is the wrong choice.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js, Vite and TypeScript logos.

Promise.all takes a list of promises and returns one promise that fulfills with a list of their results, in the order you passed them, or rejects as soon as any one of them rejects. That sentence hides three details that cause bugs: "parallel" really means "already started", the first rejection wins while the others keep running, and a plain value in the list is allowed. This post covers each on Node.js 24 with printed output, shows where Promise.all saves time, then lists the situations where it is the wrong tool and what to use instead. The common companions, [Promise.allSettled](/library/promise-allsettled-wait-everything) and [Promise.race](/library/promise-race-first-settle-wins), are covered separately.

The basic behavior

JavaScript
const delay = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));

const results = await Promise.all([
  delay(30, "slow"),
  delay(10, "fast"),
  delay(20, "medium"),
]);

console.log(results);
Text
[ 'slow', 'fast', 'medium' ]

The fast promise finished first, and it is still second in the result. The array always matches the input order, not completion order. That is what makes destructuring safe: const [user, posts] = await Promise.all([getUser(), getPosts()]) pairs each name with the right call.

Why parallel is a slight exaggeration

Promise.all does not start anything. By the time you call it, every promise in the array already exists, which means its work has already begun. What Promise.all does is wait for all of them together instead of one after another.

JavaScript
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

let start = Date.now();
await delay(20);
await delay(20);
await delay(20);
const sequential = Date.now() - start;

start = Date.now();
await Promise.all([delay(20), delay(20), delay(20)]);
const together = Date.now() - start;

console.log("sequential took at least 60 ms:", sequential >= 55);
console.log("together took under 50 ms:", together < 50);
Text
sequential took at least 60 ms: true
together took under 50 ms: true

The exact times vary by machine, so the checks use generous thresholds. Three 20 ms waits cost about 60 ms in sequence and about 20 ms together. The first block started each timer only after the previous one finished. In the second, all three timers were created while building the array, so they ran at once. This also means Promise.all cannot limit concurrency. If the array holds 5,000 requests, all 5,000 are already in flight.

Fail fast

The first rejection settles the combined promise, with that error.

JavaScript
const delay = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));

const failAfter = (ms, message) =>
  new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));

try {
  await Promise.all([
    delay(50, "ok"),
    failAfter(10, "first failure"),
    failAfter(20, "second failure"),
  ]);
} catch (error) {
  console.log("rejected with:", error.message);
}
Text
rejected with: first failure

The second failure rejection happened later and was ignored. It is not reported as unhandled, because Promise.all attached handlers to every input. But the other operations did not stop. The 50 ms timer still ran. A rejection from Promise.all means "give up waiting", not "cancel the work". If the work holds resources or costs money, pass an AbortSignal to each operation and abort on failure.

Non-promise values and empty arrays

Any value that is not a promise is treated as Promise.resolve(value), so mixed arrays work. An empty array fulfills right away with [].

JavaScript
console.log(await Promise.all([1, Promise.resolve(2), "three"]));
console.log(await Promise.all([]));
Text
[ 1, 2, 'three' ]
[]

Input does not have to be an array. Any iterable works, including a Set or a generator.

JavaScript
const set = new Set([Promise.resolve("a"), Promise.resolve("b")]);

console.log(await Promise.all(set));
console.log(await Promise.all([1, 2, 3].map(async (n) => n * 2)));
Text
[ 'a', 'b' ]
[ 2, 4, 6 ]

The second line is the usual pattern: map with an async function produces an array of promises, and Promise.all waits for them. It is the correct replacement for forEach with await, which does not wait.

Waiting for dependent work

When one step needs another's result, those two cannot run together. Use Promise.all only for the independent parts.

JavaScript
const getUser = () => Promise.resolve({ id: 7, name: "Ada" });
const getSettings = () => Promise.resolve({ theme: "dark" });
const getPosts = (id) => Promise.resolve([`post by ${id}`]);

const [user, settings] = await Promise.all([getUser(), getSettings()]);
const posts = await getPosts(user.id);

console.log(user.name, settings.theme, posts);
Text
Ada dark [ 'post by 7' ]

User and settings did not depend on each other, so they started together. Posts needed the user's id, so it had to wait.

The cost of getting concurrency wrong

Because all work starts at once, a large Promise.all can overwhelm the thing it calls: a database with a connection limit, an API with a rate limit, a machine that runs out of file descriptors. The fix is to process in batches.

JavaScript
async function inBatches(items, size, worker) {
  const results = [];

  for (let i = 0; i < items.length; i += size) {
    const batch = items.slice(i, i + size);
    results.push(...(await Promise.all(batch.map(worker))));
  }

  return results;
}

const doubled = await inBatches([1, 2, 3, 4, 5], 2, async (n) => n * 2);
console.log(doubled);
Text
[ 2, 4, 6, 8, 10 ]

At most two workers run at a time. A batch waits for its slowest member before the next begins, so a worker pool that keeps a fixed number in flight is more efficient, and libraries such as p-limit provide one. For a handful of requests, plain Promise.all is right.

When Promise.all is the wrong tool

You need every outcome, including failures. If one failure should not hide the rest, use Promise.allSettled, which never rejects and reports each result.

You want the fastest answer. Use Promise.race or Promise.any to take the first to settle or succeed.

Partial results matter. Promise.all discards every successful result when one fails. If the successes are useful, catch inside each promise.

JavaScript
const safe = (promise) => promise.catch((error) => ({ error: error.message }));

const results = await Promise.all([
  safe(Promise.resolve("a")),
  safe(Promise.reject(new Error("b failed"))),
  safe(Promise.resolve("c")),
]);

console.log(results);
Text
[ 'a', { error: 'b failed' }, 'c' ]

A real mistake we have made

The first time we parallelized a report that fetched forty pages from one API, the total time dropped and the API started returning rate-limit errors, and Promise.all rejected on the first one, discarding thirty-nine good responses. The fix was batches of five and allSettled, so a single throttled page could be retried without redoing the rest. The lesson is that fail-fast is a policy, and it fits when the result is useless unless every part succeeds.

Choosing the right combinator

The promise combinators are easy to mix up, and the question that sorts them is what the caller does with the outcomes. If every result is needed and any failure makes the whole job pointless, use Promise.all. If every result is wanted, whatever happened, use Promise.allSettled. If only the first answer counts, use Promise.race when a failure should also count as an answer, and Promise.any when only a success should.

Teams often reach for Promise.all by default because it is the one they learned first, and that is fine when the work is all-or-nothing. The mistake is applying it to work where parts are independent, such as loading widgets on a dashboard or sending a batch of notifications. There, one slow or failed part should not discard the rest, and allSettled is the honest choice. Whichever you pick, keep the number of simultaneous operations in mind. If the list can grow to hundreds, put a limit in front of it, so you never ask a database or API for more at once than it can serve.

Testing code that uses Promise.all

Tests for a function built on Promise.all should check three things beyond the happy path. First, that results come back in input order even when the promises finish in a different order, by giving the first input the longest delay. Second, that a single rejection rejects the whole call with that error, and that the function's cleanup still runs. Third, that the function does not start more work than it should, by counting how many workers were running at once and asserting that the peak never exceeds the limit you intended. If the function is meant to be fail-fast, assert that it settles soon after the first failure and does not wait for the slow inputs. Use controllable promises from Promise.withResolvers(), so the order of events is set by the test and not by timers, and the whole suite runs in a few milliseconds without any sleeping.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.