JavaScript Promise.all, allSettled, race and any: Run Promises Together

Many real tasks are independent: checking ten API endpoints, creating five test users, loading three files. Running them one after another wastes time; running them together finishes as fast as the slowest one. JavaScript’s promise combinators, Promise.all, allSettled, race and any, start work in parallel and combine the results in different ways. In this lesson you will learn when to use each, how they handle failures, how to add timeouts, and how to avoid overloading a server by limiting how many requests run at once.

Advertisement

📖 What You’ll Learn: sequential versus parallel execution, Promise.all and its fail-fast behaviour, Promise.allSettled for complete reports, Promise.race and timeouts, Promise.any for the first success and AggregateError, Promise.withResolvers, the difference between starting and awaiting a promise, limiting concurrency, and a parallel smoke check of several endpoints.


🚦 Sequential vs Parallel

A promise starts its work when it is created, not when it is awaited. If you await each call before starting the next, the tasks run sequentially; if you start them all and then wait for the results together, they run in parallel:

📄 sequential-vs-parallel.js

const delay = (ms, value) => new Promise((r) => setTimeout(() => r(value), ms));
const rounded = (start) => Math.round((Date.now() - start) / 100) * 100;

async function main() {
  let start = Date.now();
  const a = await delay(100, "users");
  const b = await delay(100, "orders");
  const c = await delay(100, "products");
  console.log("sequential:", [a, b, c], `~${rounded(start)} ms`);

  start = Date.now();
  const results = await Promise.all([delay(100, "users"), delay(100, "orders"), delay(100, "products")]);
  console.log("parallel:  ", results, `~${rounded(start)} ms`);
}
main();

⌨️ Terminal

node sequential-vs-parallel.js

🖥️ Output

sequential: [ 'users', 'orders', 'products' ] ~300 ms
parallel:   [ 'users', 'orders', 'products' ] ~100 ms

💡 Tip: Run tasks in parallel only when they are independent. If step 2 needs the result of step 1 (log in, then use the token), it must wait.


🤝 Promise.all: All Must Succeed

Definition: Promise.all(iterable) returns a promise that fulfils with an array of all results, in the same order as the input (not the order they finished), when every promise has fulfilled. It rejects immediately when any one promise rejects (“fail fast”).

📄 all.js

const delay = (ms, value, fail) => new Promise((resolve, reject) =>
  setTimeout(() => (fail ? reject(new Error(`${value} failed`)) : resolve(value)), ms));

Promise.all([delay(30, "slow"), delay(10, "fast"), delay(20, "medium")])
  .then((results) => console.log("order kept:", results));

Promise.all([delay(30, "users"), delay(10, "orders", true), delay(20, "products")])
  .then((results) => console.log("never printed", results))
  .catch((err) => console.log("Promise.all rejected:", err.message));

Promise.all([]).then((r) => console.log("empty input:", r));
Promise.all([1, "two", delay(5, 3)]).then((r) => console.log("non-promises are fine:", r));

⌨️ Terminal

node all.js

🖥️ Output

empty input: []
non-promises are fine: [ 1, 'two', 3 ]
Promise.all rejected: orders failed
order kept: [ 'slow', 'fast', 'medium' ]

⚠️ Watch out: When Promise.all rejects, the other operations are not cancelled; they keep running, and their results are simply ignored. If they have side effects (creating records), you may need cleanup. Use an AbortController if the operations support cancellation.


📋 Promise.allSettled: Wait for Everything, Report Each

Definition: Promise.allSettled(iterable) waits until every promise has settled and never rejects. Each result is an object: { status: "fulfilled", value } or { status: "rejected", reason }.

📄 all-settled.js

const check = (name, ms, ok) => new Promise((resolve, reject) =>
  setTimeout(() => (ok ? resolve({ name, status: 200 }) : reject(new Error(`${name}: 503 Service Unavailable`))), ms));

Promise.allSettled([check("auth", 20, true), check("payments", 10, false), check("search", 15, true)])
  .then((results) => {
    for (const r of results) {
      console.log(r.status === "fulfilled" ? `✓ ${r.value.name}` : `✗ ${r.reason.message}`);
    }
    const failed = results.filter((r) => r.status === "rejected").length;
    console.log(`${results.length - failed}/${results.length} services healthy`);
  });

⌨️ Terminal

node all-settled.js

🖥️ Output

✓ auth
✗ payments: 503 Service Unavailable
✓ search
2/3 services healthy

Use allSettled when you want a complete report even if some tasks fail: health checks, cleanup of many test records, or bulk validations.


Advertisement

🏁 Promise.race: First to Settle Wins

Definition: Promise.race(iterable) settles as soon as the first promise settles, with that promise’s value or error. Its most common use is adding a timeout to an operation that has no timeout of its own:

📄 race.js

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

function withTimeout(promise, ms, label) {
  let timer;
  const timeout = new Promise((_, reject) => {
    timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms} ms`)), ms);
  });
  return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}

withTimeout(delay(20, "report ready"), 100, "report").then(console.log).catch((e) => console.log(e.message));
withTimeout(delay(500, "export ready"), 50, "export").then(console.log).catch((e) => console.log(e.message));

⌨️ Terminal

node race.js

🖥️ Output

report ready
export timed out after 50 ms
  • Clearing the timer in finally stops it from keeping the process alive after the race is decided.
  • The losing operation is not cancelled; it continues in the background. For fetch, prefer AbortSignal.timeout(ms), which really cancels the request.

🥇 Promise.any: First Success Wins

Definition: Promise.any(iterable) fulfils with the value of the first promise that fulfils, ignoring rejections. It rejects only if all of them reject, with an AggregateError whose errors array holds every reason.

📄 any.js

const mirror = (name, ms, ok) => new Promise((resolve, reject) =>
  setTimeout(() => (ok ? resolve(`downloaded from ${name}`) : reject(new Error(`${name} unreachable`))), ms));

Promise.any([mirror("eu", 30, true), mirror("us", 10, false), mirror("asia", 20, true)])
  .then((result) => console.log("any:", result));

Promise.any([mirror("eu", 10, false), mirror("us", 20, false)])
  .catch((err) => console.log(err.name, "-", err.errors.map((e) => e.message).join(", ")));

⌨️ Terminal

node any.js

🖥️ Output

any: downloaded from asia
AggregateError - eu unreachable, us unreachable

The us mirror failed first, but any ignored it and waited for the first success.


⚖️ Choosing the Right Combinator

MethodFulfils whenRejects whenUse for
Promise.allAll fulfil (array of values)The first one rejectsIndependent steps that must all succeed
Promise.allSettledAll settle (array of status objects)NeverReports, health checks, bulk cleanup
Promise.raceThe first to settle fulfilsThe first to settle rejectsTimeouts, “whichever happens first”
Promise.anyThe first to fulfilAll reject (AggregateError)Fallbacks, redundant sources
Advertisement

Promise.withResolvers

Promise.withResolvers() (ES2024) returns { promise, resolve, reject } together. It is handy when the code that settles a promise is not inside the executor, for example when an event arrives later:

📄 with-resolvers.js

const { promise, resolve } = Promise.withResolvers();

const events = new (require("node:events"))();
events.once("download-finished", (file) => resolve(file));

setTimeout(() => events.emit("download-finished", "report.pdf"), 20);
promise.then((file) => console.log("download finished:", file));

⌨️ Terminal

node with-resolvers.js

🖥️ Output

download finished: report.pdf

🚥 Limiting Concurrency

Starting 500 requests at once with Promise.all can overload a test server, hit rate limits (HTTP 429) or exhaust connections. A small pool runs at most N tasks at a time and starts a new one whenever one finishes:

📄 limit.js

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

async function mapWithLimit(items, limit, worker) {
  const results = new Array(items.length);
  let next = 0, running = 0, maxRunning = 0;

  async function runNext() {
    while (next < items.length) {
      const index = next++;
      running++;
      maxRunning = Math.max(maxRunning, running);
      results[index] = await worker(items[index]);
      running--;
    }
  }

  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, runNext));
  return { results, maxRunning };
}

const userIds = Array.from({ length: 10 }, (_, i) => i + 1);
mapWithLimit(userIds, 3, async (id) => {
  await delay(10);
  return `user-${id}`;
}).then(({ results, maxRunning }) => {
  console.log(results.join(" "));
  console.log("never more than", maxRunning, "requests at once");
});

⌨️ Terminal

node limit.js

🖥️ Output

user-1 user-2 user-3 user-4 user-5 user-6 user-7 user-8 user-9 user-10
never more than 3 requests at once

Three “workers” pull from a shared queue, so results stay in input order and the server never sees more than three requests at a time. Libraries such as p-limit provide the same feature.


🧪 Tester Scenario: A Parallel Smoke Check

Before running a long test suite, a quick smoke check confirms the key endpoints are up. They are independent, so they run in parallel; each has a timeout; and allSettled produces a full report instead of stopping at the first problem:

📄 smoke.js

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

const fakeServer = {
  "/health": { ms: 20, status: 200 },
  "/api/login": { ms: 30, status: 200 },
  "/api/search": { ms: 400, status: 200 },     // too slow
  "/api/payments": { ms: 25, status: 503 },
};
const get = async (path) => {
  const { ms, status } = fakeServer[path];
  await delay(ms);
  if (status >= 400) throw new Error(`${path} returned ${status}`);
  return { path, status };
};
const timeout = (p, ms, path) => Promise.race([p, delay(ms).then(() => { throw new Error(`${path} timed out after ${ms} ms`); })]);

async function smokeCheck(paths) {
  const results = await Promise.allSettled(paths.map((p) => timeout(get(p), 200, p)));
  const failures = results.filter((r) => r.status === "rejected").map((r) => r.reason.message);
  for (const r of results) console.log(r.status === "fulfilled" ? `✓ ${r.value.path}` : `✗ ${r.reason.message}`);
  console.log(failures.length ? `SMOKE FAILED (${failures.length}/${paths.length})` : "SMOKE PASSED");
}

smokeCheck(Object.keys(fakeServer));

⌨️ Terminal

node smoke.js

🖥️ Output

✓ /health
✓ /api/login
✗ /api/search timed out after 200 ms
✗ /api/payments returned 503
SMOKE FAILED (2/4)

The whole check takes about as long as the slowest allowed request (the 200 ms timeout), not the sum of all four.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Use Promise.all to wait for three delayed values (10, 20 and 30 ms) and print their sum.

Show answer

📄 practice1.js

const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
Promise.all([delay(10, 1), delay(20, 2), delay(30, 3)])
  .then((values) => console.log(values.reduce((a, b) => a + b, 0)));

🖥️ Output

6

Q2. Use Promise.allSettled on one fulfilled and one rejected promise, and print how many succeeded.

Show answer

📄 practice2.js

Promise.allSettled([Promise.resolve("ok"), Promise.reject(new Error("bad"))])
  .then((results) => console.log(results.filter((r) => r.status === "fulfilled").length, "succeeded"));

🖥️ Output

1 succeeded

Q3. Write timeout(ms) that returns a promise rejecting after ms, and use it with Promise.race to give up on a 300 ms task after 50 ms.

Show answer

📄 practice3.js

const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
const timeout = (ms) => new Promise((_, reject) => setTimeout(() => reject(new Error(`timeout ${ms} ms`)), ms));
Promise.race([delay(300, "done"), timeout(50)])
  .then(console.log)
  .catch((e) => console.log("gave up:", e.message));

🖥️ Output

gave up: timeout 50 ms

The script keeps running until the 300 ms timer ends, because race does not cancel the slower promise.

Q4. Use Promise.any to get the first successful result from three sources where the first two fail.

Show answer

📄 practice4.js

Promise.any([
  Promise.reject(new Error("cache miss")),
  Promise.reject(new Error("replica down")),
  Promise.resolve("primary database"),
]).then((source) => console.log("served from", source));

🖥️ Output

served from primary database

Q5. Predict the output, then run it.

Promise.all([Promise.resolve(1), Promise.reject(new Error("x")), Promise.resolve(3)])
  .then((v) => console.log("then", v))
  .catch((e) => console.log("catch", e.message));
Promise.allSettled([Promise.resolve(1), Promise.reject(new Error("x"))])
  .then((r) => console.log(r.map((x) => x.status)));
Show answer

📄 practice5.js

Promise.all([Promise.resolve(1), Promise.reject(new Error("x")), Promise.resolve(3)])
  .then((v) => console.log("then", v))
  .catch((e) => console.log("catch", e.message));
Promise.allSettled([Promise.resolve(1), Promise.reject(new Error("x"))])
  .then((r) => console.log(r.map((x) => x.status)));

🖥️ Output

[ 'fulfilled', 'rejected' ]
catch x

Q6. Create 6 “test users” in parallel but with at most 2 at a time, using a simple loop over batches of 2 and Promise.all per batch.

Show answer

📄 practice6.js

const delay = (ms) => new Promise((r) => setTimeout(r, ms));
const createUser = async (n) => { await delay(10); return `user${n}`; };

async function main() {
  const ids = [1, 2, 3, 4, 5, 6];
  const created = [];
  for (let i = 0; i < ids.length; i += 2) {
    const batch = ids.slice(i, i + 2);
    created.push(...(await Promise.all(batch.map(createUser))));
    console.log("batch done:", batch.join(","));
  }
  console.log(created);
}
main();

🖥️ Output

batch done: 1,2
batch done: 3,4
batch done: 5,6
[ 'user1', 'user2', 'user3', 'user4', 'user5', 'user6' ]

Batches are simpler than a pool, but a slow task holds up its whole batch; the pool in this lesson keeps exactly N tasks running.


🧠 MCQ Quiz: Promise.all, allSettled, race, any

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does Promise.all do when one promise rejects?
  2. In what order does Promise.all return results?
  3. Which method never rejects?
  4. What does Promise.race settle with?
  5. When does Promise.any reject?
  6. Three independent 100 ms requests are awaited one after another. How long does it take?
  7. Does Promise.race cancel the slower promises?
  8. What does Promise.allSettled return for a rejected promise?
  9. Why limit concurrency when calling an API?
  10. What does Promise.all([]) return?

💼 Interview Questions and Answers

Q1. What is the difference between Promise.all and Promise.allSettled?

Promise.all fulfils with an array of values only if every promise fulfils, and rejects as soon as one rejects, so you lose the other results. Promise.allSettled waits for every promise and always fulfils with { status, value | reason } objects, so you can report each success and failure. Use all when every step is required; use allSettled for reports, health checks and cleanup.

Q2. How do you add a timeout to a promise?

Race it against a promise that rejects after the timeout: Promise.race([work, timeout(ms)]), clearing the timer in finally. Note that this does not cancel work. For APIs that accept an AbortSignal, such as fetch, pass AbortSignal.timeout(ms) to actually abort the operation.

Q3. How would you run 1,000 API calls without overloading the server?

Use a concurrency limit: a pool of N workers pulling from a queue (or a library such as p-limit), so at most N requests are in flight. Handle failures per item (allSettled-style results), respect rate-limit responses (429 with Retry-After), and add retries with back-off for transient errors. Batching in fixed groups is a simpler but less efficient alternative.

Q4. Explain what is wrong with this code.

📄 slow-fast.js

const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));

async function slow() {
  const results = [];
  for (const id of [1, 2, 3]) {
    results.push(await delay(50, id));   // waits for each one before starting the next
  }
  return results;
}

async function fast() {
  return Promise.all([1, 2, 3].map((id) => delay(50, id)));
}

(async () => {
  let t = Date.now();
  await slow();
  console.log("slow ~", Math.round((Date.now() - t) / 50) * 50, "ms");
  t = Date.now();
  await fast();
  console.log("fast ~", Math.round((Date.now() - t) / 50) * 50, "ms");
})();

⌨️ Terminal

node slow-fast.js

🖥️ Output

slow ~ 200 ms
fast ~ 50 ms

The loop awaits each independent call before starting the next, so the total time is the sum. Starting them all with map and awaiting Promise.all takes only as long as the slowest call. Keep the sequential version only when calls depend on each other or must be rate-limited.


Advertisement

❓ Frequently Asked Questions

🤔 Does Promise.all run promises in parallel?

The promises are already running when you create them; Promise.all just waits for them together. JavaScript still runs your callbacks on one thread, but the I/O happens concurrently.

🤔 Can I use Promise.all with async functions?

Yes: await Promise.all(items.map(async (item) => {...})) is the standard pattern for running async work on every item in parallel.

🤔 What is the difference between race and any?

race settles with the first promise to settle, even if it is a failure. any waits for the first success and only fails if all fail.

🤔 Are these methods supported everywhere?

Yes. all and race are ES2015, allSettled ES2020, any ES2021 and withResolvers ES2024, all available in current browsers and Node.js.


🏁 Summary

  • A promise starts when created: start independent tasks together and await them with a combinator.
  • Promise.all needs every promise to succeed and rejects on the first failure.
  • Promise.allSettled waits for all and reports each result; it never rejects.
  • Promise.race takes the first to settle (timeouts); Promise.any takes the first success (fallbacks).
  • None of them cancel the losers; limit concurrency with a pool when calling real servers.

Next, continue with Lesson 50: Async/Await.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in