
Most real pages need more than one piece of data. A dashboard wants the user, their orders and their notifications. A product page wants details, stock and reviews. If you `await` each request in turn, the page waits for the total of all of them. `Promise.all` lets you wait for them together, so the page waits only about as long as the slowest one.
This guide covers what `Promise.all` actually does (and what it doesn't), how it fails, and when to reach for its siblings `Promise.allSettled`, `Promise.race` and `Promise.any`. It also covers two things the built-in methods don't do for you: limiting concurrency and cancelling work. All the behaviour below is checked against MDN's reference pages, linked at the end.
A Quick Refresher on Promises
A promise stands in for the result of an asynchronous operation, such as a network request or a timer. It is in one of three states:
- Pending: the operation hasn't finished yet.
- Fulfilled: it succeeded, and the promise holds a value.
- Rejected: it failed, and the promise holds a reason (usually an `Error`).
You read the outcome with `.then()` and `.catch()`, or with `await` inside an `async` function wrapped in `try`/`catch`.
What Promise.all Does
`Promise.all(iterable)` takes an array (or any iterable) and returns a single promise. According to MDN, that promise:
- fulfils with an array of every result once all the inputs have fulfilled;
- rejects as soon as any input rejects, using that first rejection reason;
- is already fulfilled with `[]` if the iterable is empty. This is the only case where it resolves synchronously.
const fast = Promise.resolve(3);
const plain = 1337; // non-promise values are passed through as-is
const slow = new Promise((resolve) => setTimeout(() => resolve("foo"), 100));
const values = await Promise.all([fast, plain, slow]);
console.log(values); // [3, 1337, "foo"]Results Come Back in Input Order
The result array matches the order of the inputs, not the order in which they finished. In the example above, `slow` finishes last but its value still lands at index 2. That's why destructuring is safe, as long as the variable names line up with the inputs. MDN warns that a mismatch here is an easy source of subtle bugs.
Promise.all Doesn't Make Anything Parallel
This is the most common misunderstanding, and the original version of this post got it wrong too. `Promise.all` doesn't start any work. The work starts when you create the promise, for example when you call `fetch()`. By the time `Promise.all` sees the array, every request is already in flight. All it does is wait for them together.
So concurrency comes from starting operations without waiting between them. `Promise.all` is just a convenient way to collect the results. It also follows that you must pass promises, not functions. MDN points out that `Promise.all([fn1, fn2])` does nothing useful, because functions aren't promises and are returned as-is. Call them first: `Promise.all([fn1(), fn2()])`.
It's also concurrency, not parallelism in the multi-core sense. JavaScript callbacks still run on one thread. The waiting (on the network, the disk, a timer) overlaps, and that's where the time savings come from.
Fail-Fast Rejection
If any input rejects, `Promise.all` rejects straight away with that reason and doesn't wait for the rest. Two details matter here:
- The other operations keep running. Rejection doesn't cancel anything. As MDN's guide to using promises puts it, the other operations continue, but their outcomes aren't available through the return value of `Promise.all`.
- Later rejections are swallowed. `Promise.all` marks all its inputs as handled, so a second failure won't trigger an `unhandledrejection` event.
Use `Promise.all` when every result is required and one failure makes the whole operation useless.
A Real Example: Loading Dashboard Data
Here is the pattern you'll write most often, in TypeScript. One gotcha: `fetch()` only rejects on network-level failures. A 404 or 500 still fulfils with a `Response`, so check `response.ok` yourself or `Promise.all` will happily hand you an error page (MDN: Using Fetch).
async function getJson<T>(url: string, signal?: AbortSignal): Promise<T> {
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error(`${url} responded with ${response.status}`);
}
return (await response.json()) as T;
}
interface User { id: string; name: string }
interface Order { id: string; total: number }
interface Notice { id: string; text: string }
async function loadDashboard(userId: string) {
// All three requests start here, before anything is awaited.
const [user, orders, notices] = await Promise.all([
getJson<User>(`/api/users/${userId}`),
getJson<Order[]>(`/api/users/${userId}/orders`),
getJson<Notice[]>(`/api/users/${userId}/notifications`),
]);
return { user, orders, notices };
}TypeScript infers a tuple here, so `user` is a `User`, `orders` is an `Order[]` and so on. If those three calls take 300 ms, 500 ms and 200 ms, awaiting them one by one costs roughly a second. With `Promise.all` it costs roughly as long as the slowest call.
Promise.allSettled: When You Need Every Outcome
Dashboards often shouldn't go blank because one widget failed. `Promise.allSettled` waits for every input to settle and never rejects. It fulfils with an array of objects, in input order, each with a `status` of `"fulfilled"` (plus a `value`) or `"rejected"` (plus a `reason`).
const results = await Promise.allSettled([
getJson<Order[]>("/api/orders"),
getJson<Notice[]>("/api/notifications"),
]);
for (const result of results) {
if (result.status === "fulfilled") {
console.log("Loaded", result.value);
} else {
console.warn("Widget failed:", result.reason);
}
}The `status` check narrows the type in TypeScript, so `result.value` and `result.reason` are only reachable on the right branch. An empty iterable gives you an already-fulfilled promise with `[]`.
Promise.race: First to Settle Wins
`Promise.race` settles the same way as whichever input settles first. If that's a fulfilment, it fulfils. If it's a rejection, it rejects. The classic use is a timeout:
const data = await Promise.race([
fetch("/api/report"),
new Promise((_, reject) =>
setTimeout(() => reject(new Error("Request timed out")), 5000),
),
]);MDN flags the catch: the loser isn't cancelled. If the timer wins, the fetch keeps its connection open. If the fetch wins, the timer keeps running. For fetches, `AbortSignal.timeout()` (covered below) is usually the better tool. Also note that `Promise.race([])` stays pending forever.
Promise.any: First Success Wins
`Promise.any` ignores rejections and fulfils with the first input that fulfils. It only rejects if every input rejects, and then it rejects with an `AggregateError`. That error's `errors` property holds every rejection reason, in input order. An empty iterable gives you an already-rejected promise.
try {
const response = await Promise.any([
fetch("https://mirror-a.example.com/data.json"),
fetch("https://mirror-b.example.com/data.json"),
]);
console.log("Fastest mirror answered:", response.url);
} catch (err) {
if (err instanceof AggregateError) {
console.error("All mirrors failed:", err.errors);
}
}This suits redundant sources, like mirrors or fallback endpoints, where any one success is enough. MDN lists `Promise.any` as widely available across browsers since September 2020, and `Promise.allSettled` since July 2020.
Limiting Concurrency
`Promise.all` has no concurrency limit. Map 5,000 IDs to `fetch()` calls and you start 5,000 requests at once. That can trip rate limits, exhaust database connections or swamp a small server. The built-in methods don't solve this, so you write a little code.
Option 1: Fixed Batches
The simplest approach runs a chunk at a time and waits for the whole chunk before starting the next:
async function inBatches<T, R>(
items: readonly T[],
size: number,
worker: (item: T) => Promise<R>,
): Promise<R[]> {
const results: R[] = [];
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;
}It's easy to read, but one slow item holds up its whole batch.
Option 2: A Worker Pool
A pool keeps a fixed number of tasks running. As soon as one finishes, the next starts:
async function mapWithLimit<T, R>(
items: readonly T[],
limit: number,
worker: (item: T, index: number) => Promise<R>,
): Promise<R[]> {
const results = new Array<R>(items.length);
let next = 0;
async function runner(): Promise<void> {
while (next < items.length) {
const index = next++; // safe: JavaScript runs this synchronously
results[index] = await worker(items[index] as T, index);
}
}
const runners = Array.from({ length: Math.min(limit, items.length) }, runner);
await Promise.all(runners);
return results;
}
// Usage: never more than 5 requests in flight.
const users = await mapWithLimit(userIds, 5, (id) => getJson<User>(`/api/users/${id}`));Results still come back in input order because each one is written to its own index. Like `Promise.all`, this rejects on the first failure, and the other runners carry on with the remaining items. Pass in an `AbortSignal` if you need them to stop.
Cancelling Work with AbortController
Since no promise combinator cancels anything, cancellation has to come from the operations themselves. For `fetch()`, that means an `AbortSignal`. Share one `AbortController` across a group of requests and abort it when the first one fails:
async function fetchAllOrNothing<T>(urls: string[]): Promise<T[]> {
const controller = new AbortController();
try {
return await Promise.all(urls.map((url) => getJson<T>(url, controller.signal)));
} catch (err) {
controller.abort(); // cancel the requests that are still running
throw err;
}
}For timeouts, `AbortSignal.timeout(ms)` gives you a signal that aborts itself. When it fires, `fetch()` rejects with a `DOMException` named `TimeoutError`. A manual `controller.abort()` produces an `AbortError` instead. `AbortSignal.any([...])` combines signals, so a user's "cancel" button and a five-second timeout can share one request:
const controller = new AbortController();
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]);
const report = await getJson<unknown>("/api/report", signal);MDN notes that with a combined signal you can't tell which source triggered the abort, so handle both error names.
Common Mistakes
1. Awaiting Inside a Loop
// Sequential: each request waits for the previous one.
const users: User[] = [];
for (const id of userIds) {
users.push(await getJson<User>(`/api/users/${id}`));
}
// Concurrent: all requests start together.
const usersFast = await Promise.all(userIds.map((id) => getJson<User>(`/api/users/${id}`)));A sequential loop is right when each step depends on the last. MDN's own advice is to prefer concurrency unless one operation needs another's result. For large lists, use the pool above rather than an unbounded `map`.
2. Forgetting to Return a Promise
Inside a `.then()` callback, or a `map` callback with braces, a missing `return` leaves the promise "floating". MDN shows the problem: the next `.then()` receives `undefined` and runs early.
// Bug: the callback returns undefined, so Promise.all doesn't wait.
await Promise.all(ids.map((id) => { fetch(`/api/items/${id}`); }));
// Fix: return the promise (or drop the braces).
await Promise.all(ids.map((id) => fetch(`/api/items/${id}`)));3. Passing Functions Instead of Promises
`Promise.all([loadUser, loadOrders])` resolves right away with the two functions themselves. Call them: `Promise.all([loadUser(), loadOrders()])`.
4. Assuming Rejection Cancels the Rest
It doesn't. If the leftover requests write data or cost money, abort them explicitly.
Which Method Should You Use?
- All results required, any failure is fatal: `Promise.all`.
- Show whatever succeeded, report the rest: `Promise.allSettled`.
- First result of any kind, e.g. a timeout: `Promise.race` (or `AbortSignal.timeout` for fetches).
- First success from redundant sources: `Promise.any`.
- Hundreds of tasks: a concurrency-limited pool built on `Promise.all`.
Getting this right is often the cheapest speed win in a slow web app. Requests that wait on each other for no reason show up as long, stepped waterfalls in the browser's network panel. If your product has those, the Tech Inject web development team can help untangle the data loading as part of a wider performance review.
Sources
Frequently Asked Questions
No. Promise.all doesn't start any work. The operations begin when you create the promises, for example by calling fetch, and Promise.all only waits for them together. They overlap because none of them waited for another to finish before starting.
The returned promise rejects immediately with that first rejection reason, and you lose access to the other results through that call. The other operations aren't cancelled. They keep running, and any later rejections are ignored. Use Promise.allSettled if you need every outcome.
An already-fulfilled promise whose value is an empty array. It's the only case where Promise.all resolves synchronously. By contrast, Promise.any with an empty iterable rejects with an AggregateError, and Promise.race with an empty iterable stays pending forever.
Promise.race settles with the first input to settle, whether that's a success or a failure. Promise.any ignores failures and fulfils with the first success. It only rejects, with an AggregateError listing every reason, if all the inputs reject.
The built-in methods have no limit, so you write one. Either process items in fixed-size batches, awaiting Promise.all for each batch, or use a worker pool that keeps a fixed number of tasks running and starts the next as each finishes. A pool keeps throughput steadier because one slow task doesn't stall a whole batch.








