Sub topic 9
Running Requests in Parallel
Real pages rarely need just one resource. A dashboard might need the current user, their projects, and their notifications all at once. If you request these one after another, the wait times add up. If you start them together, the total wait is roughly the time of the slowest request. This chapter covers how to run fetch calls concurrently, how to choose between Promise.all, Promise.allSettled, Promise.any, and Promise.race, and how to avoid the mistakes that quietly make code sequential or lose errors.
This chapter assumes you are comfortable with Promises and async/await. It also assumes you know the earlier chapters' material: checking response.ok, reading a body with response.json(), and cancelling with AbortController. Examples that use top-level await run in an ES module or in the browser console.
Sequential versus concurrent: where the time goes
A call to fetch() starts the network request right away and returns a Promise. The await keyword does not start anything. It only pauses the current function until a Promise settles. So whether requests overlap depends on when you call fetch(), not on when you await.
Here is a small helper used throughout the chapter:
async function getJson(url, init) {
const response = await fetch(url, init);
if (!response.ok) {
throw new Error(`${url}: HTTP ${response.status}`);
}
return response.json();
}This version is sequential. Each request starts only after the previous one has finished:
console.time('sequential');
const user = await getJson('https://api.example.com/user');
const projects = await getJson('https://api.example.com/projects');
const notifications = await getJson('https://api.example.com/notifications');
console.timeEnd('sequential');If each request takes 300 ms, this takes about 900 ms. This version starts all three first and waits afterwards:
console.time('concurrent');
const userPromise = getJson('https://api.example.com/user');
const projectsPromise = getJson('https://api.example.com/projects');
const notificationsPromise = getJson('https://api.example.com/notifications');
const user = await userPromise;
const projects = await projectsPromise;
const notifications = await notificationsPromise;
console.timeEnd('concurrent');It takes about 300 ms. It also has a hidden flaw. If projectsPromise rejects while the code is still awaiting userPromise, nothing is handling that rejection yet, and the browser may log an "unhandled promise rejection" warning. The Promise combinators below solve this, because they attach handlers to every Promise at once.
Go sequential only when one request needs data from another, for example when you need the user's ID before you can fetch their projects. Requests that don't depend on each other should start together.
Promise.all: all results or the first failure
Promise.all takes an iterable of Promises. It returns a Promise that fulfills with an array of results in input order, whatever order the responses arrive in. If any input rejects, the combined Promise rejects with that first reason right away.
const [user, projects, notifications] = await Promise.all([
getJson('https://api.example.com/user'),
getJson('https://api.example.com/projects'),
getJson('https://api.example.com/notifications')
]);
console.log(user.name, projects.length, notifications.length);Use Promise.all when the results only make sense together. If the page can't render without all three pieces, failing fast is the right behaviour: you show one error state instead of a half-built page.
For a list of similar resources, map the inputs to Promises:
const ids = [1, 2, 3, 4, 5];
const users = await Promise.all(
ids.map((id) => getJson(`https://api.example.com/users/${id}`))
);
console.log(users.map((u) => u.name));Fail-fast does not cancel anything
When Promise.all rejects, the other requests keep running. Their responses are downloaded and then thrown away. Promises have no built-in cancellation. To stop the remaining work, share one AbortController across the batch and abort it on the first failure:
async function getAllOrNothing(urls) {
const controller = new AbortController();
try {
return await Promise.all(
urls.map((url) => getJson(url, { signal: controller.signal }))
);
} catch (err) {
controller.abort();
throw err;
}
}
try {
const data = await getAllOrNothing([
'https://api.example.com/user',
'https://api.example.com/projects'
]);
console.log(data);
} catch (err) {
console.error('Batch failed:', err.message);
}The aborted requests reject with an AbortError. Promise.all has already settled with the first error by then, so the later rejections are ignored and no unhandled-rejection warning appears. The caller sees the original cause instead of the abort.
Promise.allSettled: keep every outcome
Sometimes partial results are useful. A news page with five widgets should still show four of them if one feed is down. Promise.allSettled never rejects. It waits for every input and fulfills with an array of outcome objects:
{ status: 'fulfilled', value }for successes{ status: 'rejected', reason }for failures
const feeds = [
'https://api.example.com/feeds/world',
'https://api.example.com/feeds/tech',
'https://api.example.com/feeds/sport'
];
const results = await Promise.allSettled(feeds.map((url) => getJson(url)));
const loaded = [];
const failed = [];
results.forEach((result, i) => {
if (result.status === 'fulfilled') {
loaded.push({ url: feeds[i], items: result.value });
} else {
failed.push({ url: feeds[i], error: result.reason.message });
}
});
console.log(`${loaded.length} feeds loaded, ${failed.length} failed`);
failed.forEach((f) => console.warn(f.url, f.error));Results stay in input order, so the index i maps each outcome back to its URL. This is the usual way to report which request failed, because reason might be an AbortError or TypeError that doesn't include the URL.
Promise.any and Promise.race: the first one wins
These two combinators settle early and don't collect everything.
Promise.any fulfills with the first input that fulfills. It ignores rejections unless every input rejects, and then it rejects with an AggregateError whose errors array holds every reason. This fits mirrors or redundant endpoints:
const mirrors = [
'https://eu.cdn.example.com/config.json',
'https://us.cdn.example.com/config.json'
];
const controller = new AbortController();
try {
const config = await Promise.any(
mirrors.map((url) => getJson(url, { signal: controller.signal }))
);
console.log('Config loaded:', config);
} catch (err) {
if (err instanceof AggregateError) {
err.errors.forEach((e) => console.error(e.message));
}
} finally {
controller.abort(); // stop the slower mirrors
}Calling abort() after the Promise has settled does nothing to the completed request and cancels any that are still running.
Promise.race settles with the first input that settles, whether it fulfills or rejects. People used to race a fetch against a timer to get a timeout. That pattern leaves the request running after the timer wins, so AbortSignal.timeout() from the previous chapter is the better choice. race is still useful when the first event of any kind should decide the outcome.
Choosing a combinator
| Combinator | Settles when | Fulfills with | Rejects with | Typical use |
|---|---|---|---|---|
| `Promise.all` | All fulfill, or first rejects | Array of values | First rejection reason | Data that is only useful together |
| `Promise.allSettled` | All settle | Array of outcome objects | Never rejects | Independent widgets, batch reports |
| `Promise.any` | First fulfills, or all reject | First fulfilled value | `AggregateError` | Mirrors, fallbacks |
| `Promise.race` | First settles | First value | First reason | First event wins either way |
Limiting concurrency
Starting 500 requests with urls.map(fetch) is technically concurrent, but it causes problems. Over HTTP/1.1, browsers allow about six connections per origin, so most requests wait in the browser's queue anyway, and you can't control the order. Over HTTP/2 the requests are multiplexed, but the server may rate-limit you with 429 Too Many Requests. Memory use also grows with every response held at once.
A concurrency limit runs at most N requests at a time and starts the next one when a slot frees up. The function below starts limit workers. Each worker takes the next unclaimed index until the list runs out:
async function mapWithLimit(items, limit, fn) {
const results = new Array(items.length);
let next = 0;
async function worker() {
while (next < items.length) {
const index = next++;
results[index] = await fn(items[index], index);
}
}
const workerCount = Math.min(limit, items.length);
await Promise.all(Array.from({ length: workerCount }, () => worker()));
return results;
}
const ids = Array.from({ length: 50 }, (_, i) => i + 1);
const users = await mapWithLimit(ids, 4, (id) =>
getJson(`https://api.example.com/users/${id}`)
);
console.log(users.length); // 50next++ is safe without locks because JavaScript runs on a single thread. Each worker claims its index synchronously before its first await. Results go into the slot for their index, so output order matches input order.
This version behaves like Promise.all: the first error rejects the whole call, but workers that are already running finish their current item first. To get allSettled behaviour, wrap the call to fn in try/catch and store an outcome object instead:
const outcomes = await mapWithLimit(ids, 4, async (id) => {
try {
return { status: 'fulfilled', value: await getJson(`https://api.example.com/users/${id}`) };
} catch (reason) {
return { status: 'rejected', reason };
}
});
console.log(outcomes.filter((o) => o.status === 'rejected').length, 'failed');Common mistakes
`await` inside `forEach`
const results = [];
ids.forEach(async (id) => {
results.push(await getJson(`https://api.example.com/users/${id}`));
});
console.log(results.length); // 0: forEach does not waitforEach ignores the Promises its callback returns. The requests do run concurrently, but nothing waits for them, the results arrive in completion order, and any rejection goes unhandled. Use Promise.all(ids.map(...)) instead.
`await` inside a `for...of` loop when requests are independent
A for...of loop with await in the body is sequential. That is correct when each step depends on the previous one, or when you want strict one-at-a-time pacing. For independent requests it wastes time.
Calling fetch too late
Promise.all([await getJson(a), await getJson(b)]) is sequential. Each await finishes before the array is built, so Promise.all only receives values that are already resolved. Pass the Promises themselves, without await.
Forgetting that bodies are part of the request
A Promise from fetch() resolves when the headers arrive. If you collect responses with Promise.all and read bodies later in a loop with await response.json(), the body downloads still overlap, but any parse errors appear outside your batch error handling. Reading the body inside the mapped function, as getJson does, keeps each request's full lifecycle in one place.
Exercise
This code takes about 1.2 seconds when each request takes 400 ms. Explain why, and rewrite it so it takes about 400 ms while still failing if any request returns an HTTP error. const a = await fetch('/api/a').then((r) => r.json()); const b = await fetch('/api/b').then((r) => r.json()); const c = await fetch('/api/c').then((r) => r.json());
Show answer
Each line awaits its request before the next fetch() is called, so the three latencies add up. Start all three first and wait on them together, checking response.ok in each: const load = async (url) => { const r = await fetch(url); if (!r.ok) throw new Error(${url}: HTTP ${r.status}); return r.json(); }; const [a, b, c] = await Promise.all(['/api/a', '/api/b', '/api/c'].map(load)); The original also never checked response.ok, so a 500 with an HTML error page would have failed later as a JSON parse error.
Exercise
A page shows weather, stock prices, and headlines in three separate panels. The stocks API sometimes returns 503. Which combinator should load the panels, and how do you know which panel failed?
Show answer
Use Promise.allSettled, because each panel is useful on its own and one failure should not blank the others. Results come back in input order, so the index of each outcome object tells you which panel it belongs to: render result.value where status is 'fulfilled' and show an error state for that panel where status is 'rejected'.
Exercise
You use Promise.all to fetch 20 files, and the third one fails after 50 ms. What happens to the other 17 requests, and how would you stop them?
Show answer
They keep downloading. Promise.all rejects with the first error but cannot cancel the underlying requests, so their responses are fetched and discarded. To stop them, create one AbortController, pass controller.signal to every fetch, and call controller.abort() in the catch block around Promise.all. The remaining requests then reject with AbortError, which Promise.all ignores because it has already settled.