Running Tasks in Parallel
Promise combinators are static methods that take several promises and return one promise that settles based on all of them. They are how you run independent async operations at the same time and wait for them in a controlled way: wait for all (Promise.all), wait for all and report each result (Promise.allSettled), take the first to finish (Promise.race), or take the first success (Promise.any). Choosing the right one, and knowing when to limit how many run at once, is the difference between a page that loads in one second and one that takes five.
In One Minute
Promise.all(promises): fulfills with an array of all values, in order; rejects as soon as one rejects.Promise.allSettled(promises): waits for all, never rejects; gives{ status, value }or{ status, reason }for each.Promise.race(promises): settles like the first promise to settle (fulfilled or rejected).Promise.any(promises): fulfills with the first fulfillment; rejects with anAggregateErroronly if all reject.- Promises start running when created: combinators only decide how to wait. Limit concurrency for large batches.
Comparing the Four
| Method | Fulfills when | Rejects when | Result |
|---|---|---|---|
Promise.all | All fulfill | Any rejects (immediately) | Array of values |
Promise.allSettled | All settle | Never | Array of { status, value / reason } |
Promise.race | The first settles as fulfilled | The first settles as rejected | One value or reason |
Promise.any | The first fulfills | All reject | One value, or an AggregateError |
All four accept any iterable (usually an array), and non-promise values are treated as already-fulfilled promises.
Promise.all
Use Promise.all when you need every result and any failure means the whole operation failed:
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms, msg) => new Promise((_, reject) => setTimeout(() => reject(new Error(msg)), ms));
const [students, settings, total] = await Promise.all([
wait(30, ["Navika", "Srihitha"]),
wait(10, { currency: "USD" }),
wait(20, 655),
]);
console.log(students.length, settings.currency, total);
try {
await Promise.all([wait(30, "slow ok"), fail(10, "Payments service down"), wait(20, "ok")]);
} catch (err) {
console.log("all rejected:", err.message);
}2 USD 655
all rejected: Payments service downExplanation: results come back in the order of the input, not the order of completion, which makes destructuring safe. In the second call, the rejection after 10 ms made Promise.all reject immediately, without waiting for the others. (Those other operations still ran to completion in the background; Promise.all simply stopped listening.)
Promise.allSettled
Use allSettled when each operation is independent and you want to handle each outcome, such as sending reminders to many students, where one failure shouldn't stop or hide the rest:
const sendReminder = (name) =>
new Promise((resolve, reject) =>
setTimeout(() => (name === "Srihitha" ? reject(new Error("Invalid email")) : resolve(`sent to ${name}`)), 10));
const names = ["Navika", "Srihitha", "Advitha"];
const results = await Promise.allSettled(names.map(sendReminder));
results.forEach((r, i) => {
console.log(names[i], r.status, r.status === "fulfilled" ? r.value : r.reason.message);
});
const failed = results.filter((r) => r.status === "rejected").length;
console.log(`${results.length - failed} sent, ${failed} failed`);Navika fulfilled sent to Navika
Srihitha rejected Invalid email
Advitha fulfilled sent to Advitha
2 sent, 1 failedEach result is an object with a status of "fulfilled" (with value) or "rejected" (with reason).
Promise.race
race settles as soon as any input settles, success or failure. Its classic use is a timeout:
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const timeoutAfter = (ms) => new Promise((_, reject) => setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms));
console.log(await Promise.race([wait(10, "fast response"), timeoutAfter(100)]));
try {
await Promise.race([wait(200, "slow response"), timeoutAfter(30)]);
} catch (err) {
console.log(err.message);
}fast response
Timed out after 30 msThe losing promise keeps running in the background, since a race doesn't cancel anything. For fetch, prefer AbortSignal.timeout, which actually cancels the request (next lesson).
Promise.any
any waits for the first success, ignoring failures unless every promise fails. Use it when several sources can provide the same thing and the fastest working one wins:
const source = (name, ms, ok) =>
new Promise((resolve, reject) => setTimeout(() => (ok ? resolve(`rates from ${name}`) : reject(new Error(`${name} failed`))), ms));
console.log(await Promise.any([source("primary", 30, false), source("backup", 20, true), source("mirror", 40, true)]));
try {
await Promise.any([source("primary", 10, false), source("backup", 20, false)]);
} catch (err) {
console.log(err.name, "-", err.errors.map((e) => e.message).join(", "));
}rates from backup
AggregateError - primary failed, backup failedWhen all reject, the AggregateError's errors array lists every reason, in input order.
Promises Start When Created
A combinator doesn't start anything: calling an async function starts its work immediately, and the combinator just waits. That's why the pattern is "create all the promises, then pass them in":
const log = [];
const task = (name, ms) => {
log.push(`start ${name}`);
return new Promise((resolve) => setTimeout(() => { log.push(`end ${name}`); resolve(name); }, ms));
};
const promises = [task("A", 30), task("B", 10)];
log.push("both started before Promise.all");
await Promise.all(promises);
console.log(log.join(" | "));start A | start B | both started before Promise.all | end B | end ABoth tasks were already running when Promise.all was called.
Limiting Concurrency
Promise.all(items.map(fetchItem)) starts every request at once. For 5 items that's ideal; for 5,000 it can overwhelm the server (or trigger rate limiting, HTTP 429), exhaust connections, or use too much memory. Limit how many run at the same time with a small pool:
async function mapWithLimit(items, limit, fn) {
const results = new Array(items.length);
let next = 0;
async function worker() {
while (next < items.length) {
const i = next++;
results[i] = await fn(items[i], i);
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
return results;
}
let running = 0;
let maxRunning = 0;
const save = async (id) => {
running++;
maxRunning = Math.max(maxRunning, running);
await new Promise((r) => setTimeout(r, 10));
running--;
return `saved ${id}`;
};
const ids = Array.from({ length: 20 }, (_, i) => i + 1);
const out = await mapWithLimit(ids, 4, save);
console.log(out.length, out[0], out[19]);
console.log("never more than 4 at once:", maxRunning === 4);20 saved 1 saved 20
never more than 4 at once: trueExplanation: four "workers" each take the next item, process it, and loop until none are left, so at most four requests are ever in flight. Results are stored by index, so they stay in input order. Libraries such as p-limit provide the same thing.
Sequential, Parallel or Limited?
| Situation | Approach |
|---|---|
| Each step needs the previous result | Sequential: await one after another |
| A few independent operations, all required | await Promise.all([...]) |
| Many independent operations, report each | Promise.allSettled |
| Hundreds or thousands of requests | A concurrency pool (mapWithLimit) |
| Order of side effects matters (writing a log, a ledger) | Sequential for...of |
| Several sources, fastest success wins | Promise.any |
| Something must finish within a deadline | AbortSignal.timeout or Promise.race |
In Practice
The Fee Tracker's nightly job sends receipts for every payment, at most three at a time, and produces a report of successes and failures without letting one failure stop the batch:
const sendReceipt = (p) =>
new Promise((resolve, reject) =>
setTimeout(() => (p.email ? resolve(p.id) : reject(new Error(`no email for payment ${p.id}`))), 5));
async function mapSettledWithLimit(items, limit, fn) {
const results = [];
for (let i = 0; i < items.length; i += limit) {
const batch = items.slice(i, i + limit);
results.push(...(await Promise.allSettled(batch.map(fn))));
}
return results;
}
const payments = [1, 2, 3, 4, 5, 6, 7].map((id) => ({ id, email: id !== 4 && id !== 6 }));
const results = await mapSettledWithLimit(payments, 3, sendReceipt);
const sent = results.filter((r) => r.status === "fulfilled").map((r) => r.value);
const errors = results.filter((r) => r.status === "rejected").map((r) => r.reason.message);
console.log("sent:", sent.join(", "));
console.log("errors:", errors);sent: 1, 2, 3, 5, 7
errors: ['no email for payment 4', 'no email for payment 6']This simpler batching version waits for each group of three to finish before starting the next; the worker pool shown earlier keeps all slots busy and is faster when durations vary.
Common Mistakes
Awaiting independent calls in sequence. Start them all, then await Promise.all.
Using Promise.all when partial results matter. One failure hides all successes. Use allSettled.
Firing thousands of requests at once. Limit concurrency.
Thinking race cancels the losers. They keep running. Cancel explicitly with AbortController.
Interview Corner
What is the difference between Promise.all and Promise.allSettled?
Promise.all fulfills with all values in input order but rejects immediately when any input rejects. Promise.allSettled always waits for every input and fulfills with an array of outcome objects ({ status: "fulfilled", value } or { status: "rejected", reason }); it never rejects.
What is the difference between race and any?
race settles with the first input to settle, whether it fulfilled or rejected. any fulfills with the first fulfillment, ignoring rejections, and rejects with an AggregateError only if all inputs reject.
Implement Promise.all.
Show solution
function promiseAll(items) {
return new Promise((resolve, reject) => {
const list = [...items];
const results = new Array(list.length);
let remaining = list.length;
if (remaining === 0) return resolve(results);
list.forEach((item, i) => {
Promise.resolve(item).then((value) => {
results[i] = value;
if (--remaining === 0) resolve(results);
}, reject);
});
});
}
const wait = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
console.log(await promiseAll([wait(20, "a"), 2, wait(5, "c")]));
console.log(await promiseAll([]));['a', 2, 'c']
[]Results are stored by index so order is preserved; the first rejection calls reject, and later calls to resolve or reject are ignored because a promise settles only once.
Practice
Challenge: Use Promise.any to return the first available exchange rate from three sources, falling back to 1 if all fail.
Show solution
const source = (rate, ms, ok) => new Promise((resolve, reject) => setTimeout(() => (ok ? resolve(rate) : reject(new Error("down"))), ms));
async function firstRate(sources) {
try {
return await Promise.any(sources);
} catch {
return 1;
}
}
console.log(await firstRate([source(1.08, 30, true), source(1.07, 10, false), source(1.09, 20, true)]));
console.log(await firstRate([source(1.08, 10, false), source(1.07, 10, false)]));1.09
1Key Takeaways
| Need | Use |
|---|---|
| All results, any failure is fatal | Promise.all |
| Every outcome, success or failure | Promise.allSettled |
| First to finish (often a timeout) | Promise.race |
| First success from several sources | Promise.any |
| Many requests, gently | A concurrency pool |
Was this tutorial helpful?