Sub topic 9
Running Requests in Parallel
This chapter assumes you can write async functions, check response.ok before parsing a body, and read JSON with response.json(). Earlier chapters covered those steps. Here you will start several requests at the same time and collect their results.
Sequential Versus Concurrent
When you await each request in turn, each one waits for the one before it to finish. With three requests that each take 300 ms, the whole job takes about 900 ms.
// Sequential: each request starts only after the previous one finishes
const users = await (await fetch('https://api.example.com/users')).json();
const posts = await (await fetch('https://api.example.com/posts')).json();
const comments = await (await fetch('https://api.example.com/comments')).json();Calling fetch() starts the request right away and returns a Promise. If you call fetch() several times before awaiting any of the results, the requests run at the same time. The total time is then close to the time of the slowest request, so the example above would take about 300 ms instead of 900 ms.
Only make requests concurrent when they don't depend on each other. If the second request needs an ID from the first response, it has to wait for that response.
Promise.all: All or Nothing
Promise.all takes an array of Promises. It resolves with an array of values in the same order as the input, whatever order the responses actually arrive in. It rejects as soon as any one of the Promises rejects.
async function getJson(url) {
const response = await fetch(url);
if (!response.ok) throw new Error(`${url}: HTTP ${response.status}`);
return response.json();
}
try {
const [users, posts, comments] = await Promise.all([
getJson('https://api.example.com/users'),
getJson('https://api.example.com/posts'),
getJson('https://api.example.com/comments')
]);
console.log(users.length, posts.length, comments.length);
} catch (err) {
console.error('At least one request failed:', err.message);
}Each request goes through getJson, so an HTTP status such as 404 or 500 becomes a rejection. Without that check, Promise.all would treat an error page as a success, because fetch only rejects on network failure.
Use Promise.all when the page can't do anything useful unless every request succeeds. One example is a page that needs both a user record and that user's permissions before it can show anything.
Promise.allSettled: Keep Every Result
Promise.allSettled waits for every Promise to finish and never rejects. Each entry in the result array is an object with one of two shapes:
| `status` | Extra property | Meaning |
|---|---|---|
| `'fulfilled'` | `value` | The Promise resolved with this value |
| `'rejected'` | `reason` | The Promise rejected with this error |
const urls = [
'https://api.example.com/users',
'https://api.example.com/posts',
'https://api.example.com/comments'
];
const results = await Promise.allSettled(
urls.map(async (url) => {
const response = await fetch(url);
if (!response.ok) throw new Error(`${url}: HTTP ${response.status}`);
return response.json();
})
);
for (const result of results) {
if (result.status === 'fulfilled') {
console.log('Data:', result.value);
} else {
console.warn('Failed:', result.reason.message);
}
}The urls.map(async ...) pattern starts every request during the map call, and each callback handles its own status check. Use allSettled for dashboards and other pages made of independent widgets, where one broken panel shouldn't blank the whole page.
Common Mistakes
- Awaiting inside a
forloop. Writingfor (const url of urls) { await fetch(url); }runs the requests one at a time. Build an array of Promises first, then await them together. - Skipping the
okcheck. Neither combinator knows about HTTP statuses. Do the check inside each request function. - Firing hundreds of requests at once. Browsers limit how many connections they open to one origin, and servers may rate-limit you. For large lists, process the URLs in batches, for example 5 or 10 at a time.
Exercise
A page loads a product, its reviews, and recommended items. The product is required, but the other two are optional. Which combinator would you use, and how would you treat a failed product request?
Show answer
Use Promise.allSettled so a failed reviews or recommendations request doesn't discard the other results. After it settles, check the product entry first. If its status is 'rejected', throw or show an error page. For the optional entries, show their data when fulfilled and hide those sections when rejected.
Exercise
Why does this code take about as long as three back-to-back requests: const a = await getJson(u1); const b = await getJson(u2); const c = await getJson(u3);?
Show answer
Each await pauses the function until that request finishes, so getJson(u2) isn't called until the first request completes. Start all three first, for example with Promise.all([getJson(u1), getJson(u2), getJson(u3)]), so they overlap.