Promise.all, allSettled, race and any: Running Promises in Parallel in JavaScript
Run async work concurrently with the promise combinators: Promise.all for all-or-nothing results, allSettled for partial success, race for timeouts, any for first success and AggregateError. Plus sequential vs parallel, when promises start, limiting concurrency, and common mistakes.
kvi5hnuCode Sprout team member6 min readOn this page
Chains (article 96) run steps one after another. Often the steps don't depend on each other: a dashboard needs the user, their notifications and the weather, and there's no reason to wait for one before requesting the next. Starting them all at once and combining the results is faster, and JavaScript provides four promise combinators for it. All four take an iterable (usually an array) of promises or plain values and return a single promise.

| Combinator | Fulfills when | Rejects when | Typical use |
|---|---|---|---|
Promise.all | all fulfill (array of values) | any rejects (first reason) | load everything a page needs |
Promise.allSettled | all settle (array of status objects) | never | batch jobs where some may fail |
Promise.race | the first to settle fulfills | the first to settle rejects | timeouts |
Promise.any | the first fulfills | all reject (AggregateError) | fastest of several mirrors |
Sequential vs parallel
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const start = Date.now();
delay(30, "user")
.then(() => delay(30, "orders"))
.then(() => delay(30, "prefs"))
.then(() => console.log("sequential took about 90 ms:", Date.now() - start >= 90));
Promise.all([delay(30, "user"), delay(30, "orders"), delay(30, "prefs")])
.then((values) => console.log("parallel took about 30 ms:", Date.now() - start < 60, values));
parallel took about 30 ms: true [ 'user', 'orders', 'prefs' ]
sequential took about 90 ms: true
Parallel total time is roughly the slowest operation, not the sum. ("Parallel" here means concurrent waiting: JavaScript still runs your code on one thread, but the network and timers wait simultaneously.)
Promises start when they're created
The combinators don't start anything. A promise represents work that's already running, so the work begins when you call the function that returns it:
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const started = [];
const task = (name) => {
started.push(name);
return delay(5, name);
};
const promises = ["a", "b", "c"].map(task); // all three start here
console.log("started:", started.join(", "));
Promise.all(promises).then((r) => console.log("done:", r.join(", ")));
started: a, b, c
done: a, b, c
So [urls].map(fetch) already fires every request. If you need them to run one at a time, call each function only after the previous promise settles (a chain, reduce from article 96, or a for...of loop with await in article 98).
Promise.all: all or nothing
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const fail = (ms, msg) => new Promise((_, reject) => setTimeout(reject, ms, new Error(msg)));
Promise.all([delay(30, "user"), delay(10, "orders"), 42])
.then((results) => console.log("results in input order:", results));
Promise.all([delay(30, "user"), fail(10, "orders failed"), fail(20, "prefs failed")])
.then((results) => console.log("never runs", results))
.catch((err) => console.log("rejected with:", err.message));
rejected with: orders failed
results in input order: [ 'user', 'orders', 42 ]
- Results come back in input order, not completion order, so destructuring is safe:
const [user, orders] = await Promise.all([getUser(), getOrders()]). - Non-promise values (like
42) are passed through as already-fulfilled. Promise.all([])fulfills immediately with[].- It fails fast: the first rejection rejects the whole thing, and you get only that reason. The other operations keep running (promises can't be cancelled); their results are simply ignored. Use an
AbortControllerto actually stop requests you no longer need.
Use Promise.all when you need every result and one failure makes the whole result useless.
Promise.allSettled: every outcome
Promise.allSettled (ES2020) never rejects. It waits for everything and describes each outcome:
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const fail = (ms, msg) => new Promise((_, reject) => setTimeout(reject, ms, msg));
Promise.allSettled([delay(10, "photo-1 uploaded"), fail(5, "photo-2 too large"), delay(15, "photo-3 uploaded")])
.then((results) => {
console.log(results);
const ok = results.filter((r) => r.status === "fulfilled").map((r) => r.value);
const failed = results.filter((r) => r.status === "rejected").map((r) => r.reason);
console.log(`${ok.length} succeeded, ${failed.length} failed:`, failed);
});
[
{ status: 'fulfilled', value: 'photo-1 uploaded' },
{ status: 'rejected', reason: 'photo-2 too large' },
{ status: 'fulfilled', value: 'photo-3 uploaded' }
]
2 succeeded, 1 failed: [ 'photo-2 too large' ]
Each result is { status: "fulfilled", value } or { status: "rejected", reason }. Use it for independent jobs where partial success is fine: uploading several files, sending notifications, loading optional dashboard widgets.
Promise.race: first to settle
Promise.race settles exactly like whichever input settles first, fulfilled or rejected:
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const fail = (ms, msg) => new Promise((_, reject) => setTimeout(reject, ms, new Error(msg)));
Promise.race([delay(20, "slow server"), delay(10, "fast server")]).then((v) => console.log("winner:", v));
Promise.race([delay(20, "data"), fail(10, "connection reset")]).catch((e) => console.log("race rejected:", e.message));
winner: fast server
race rejected: connection reset
Its classic use is a timeout:
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
function withTimeout(promise, ms) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`timed out after ${ms} ms`)), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
withTimeout(delay(50, "report"), 10).catch((err) => console.log(err.message));
withTimeout(delay(5, "quick report"), 50).then((v) => console.log("got", v));
got quick report
timed out after 10 ms
The finally clears the timer so it doesn't keep a Node process alive after the real work wins. Remember that the losing operation keeps running; for fetch, prefer fetch(url, { signal: AbortSignal.timeout(ms) }), which actually cancels the request.
Promise.race([]) never settles, because nothing can win.
Promise.any: first success
Promise.any (ES2021) fulfills with the first fulfilled input and ignores rejections, unless every input rejects:
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const fail = (ms, msg) => new Promise((_, reject) => setTimeout(reject, ms, new Error(msg)));
Promise.any([fail(5, "mirror 1 down"), delay(20, "mirror 2"), delay(10, "mirror 3")])
.then((v) => console.log("loaded from", v));
Promise.any([fail(5, "mirror 1 down"), fail(10, "mirror 2 down")])
.catch((err) => console.log(err.name, "-", err.errors.map((e) => e.message)));
loaded from mirror 3
AggregateError - [ 'mirror 1 down', 'mirror 2 down' ]
When all inputs reject, the result is an AggregateError whose errors array holds every reason, in input order. Promise.any([]) rejects immediately with an AggregateError.
race vs any: race answers "what happened first?", including failures; any answers "did anything succeed, and which was first?".
Limiting concurrency
Promise.all with 10,000 URLs fires 10,000 requests at once, which can overwhelm servers, hit rate limits or exhaust memory. A small worker pool keeps at most N operations in flight:
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
function mapWithLimit(items, limit, fn) {
const results = new Array(items.length);
let next = 0;
let active = 0;
let peak = 0;
function worker() {
if (next >= items.length) return Promise.resolve();
const index = next++;
active++;
peak = Math.max(peak, active);
return fn(items[index]).then((result) => {
results[index] = result;
active--;
return worker(); // pick up the next item
});
}
const workers = Array.from({ length: Math.min(limit, items.length) }, worker);
return Promise.all(workers).then(() => ({ results, peak }));
}
mapWithLimit([1, 2, 3, 4, 5, 6], 2, (n) => delay(5 * (7 - n), n * 10))
.then(({ results, peak }) => console.log(results, "max in flight:", peak));
[ 10, 20, 30, 40, 50, 60 ] max in flight: 2
Each "worker" takes the next item when it finishes one, and results are stored by index so order is preserved. Libraries like p-limit package the same idea. (With async/await this helper gets even shorter.)
Common mistakes
- Passing functions instead of promises:
Promise.all([getUser, getOrders])fulfills immediately with the functions themselves. Call them:Promise.all([getUser(), getOrders()]). - Forgetting
returninsidemap:items.map((x) => { save(x); })produces an array ofundefined, soPromise.allhas nothing to wait for. Useitems.map((x) => save(x))orreturn save(x). - Using
allwhen partial results are acceptable: one failed widget shouldn't blank the whole dashboard; useallSettled. - Assuming failure cancels the others: it doesn't; the remaining work continues in the background.
- Using
forEachwith async callbacks:forEachignores returned promises; usemapplusPromise.all.
Common questions
Does Promise.all run things in parallel?
It doesn't run anything; it waits. The operations run concurrently because they were all started (by calling their functions) before you waited on them.
In what order are Promise.all results returned?
In the same order as the input, regardless of which finished first.
How do I get partial results when some promises fail?
Use Promise.allSettled, then filter the results by status.
What's the difference between race and any?
race settles with the first input to settle, even if that's a rejection. any waits for the first fulfillment and only rejects (with AggregateError) if everything rejects.
Summary
- Start independent operations together and combine them; total time is about the slowest one.
- Promises start when created; combinators only wait for results.
Promise.all: every value in input order, rejects on the first failure.Promise.allSettled: never rejects; returns{ status, value | reason }for every input.Promise.race: first to settle wins (timeouts);Promise.any: first to fulfill wins,AggregateErrorif all fail.- Rejection doesn't cancel the other operations; use
AbortControllerfor that, and limit concurrency for large batches.
Practice Questions
What does this print?
Promise.all([1, Promise.resolve(2), Promise.reject(new Error("3"))])
.then((v) => console.log("values", v))
.catch((e) => console.log("error", e.message));
Answer
error 3. One rejected input rejects the whole Promise.all.
Which combinator fits each case? (a) Show a page only when the profile, settings and permissions have all loaded. (b) Send 50 notification emails and report how many failed. (c) Load a script from whichever of three CDNs responds successfully first. (d) Give up on a request after 5 seconds.
Answer
(a) Promise.all, (b) Promise.allSettled, (c) Promise.any, (d) Promise.race with a timeout promise (or AbortSignal.timeout for fetch).
Why does this log an empty array immediately, before the files are saved?
const results = [];
files.forEach((f) => save(f).then((r) => results.push(r)));
console.log(results);
Answer
forEach doesn't wait for the promises, so console.log runs before any save finishes. Collect the promises and wait for them:
Promise.all(files.map((f) => save(f))).then((results) => console.log(results));
What does this print?
Promise.any([Promise.reject(new Error("a")), Promise.reject(new Error("b"))])
.catch((e) => console.log(e instanceof AggregateError, e.errors.length));
Answer
true 2. All inputs rejected, so any rejects with an AggregateError holding both reasons.
Next: JavaScript async and await: Writing Asynchronous Code That Reads Like Synchronous Code

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.