Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions 5-network/01-fetch/01-fetch-users/solution.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,18 @@ Please note: `.then` call is attached directly to `fetch`, so that when we have
If we used `await Promise.all(names.map(name => fetch(...)))`, and call `.json()` on the results, then it would wait for all fetches to respond. By adding `.json()` directly to each `fetch`, we ensure that individual fetches start reading data as JSON without waiting for each other.

That's an example of how low-level Promise API can still be useful even if we mainly use `async/await`.

**Alternative modern approach**

Nowadays, we can achieve the same parallel execution cleanly using pure `async/await` combined with `Promise.allSettled`.

By wrapping the `fetch` and `.json()` calls inside an `async` callback for `.map()`, we ensure the requests execute independently. `Promise.allSettled` guarantees that a hard network failure in one request won't reject the entire batch, and using `.ok` simplifies the status check:

```js demo
const getUsers = async (names) => (await Promise.allSettled(
names.map(async (name) => {
const response = await fetch(`[https://api.github.com/users/$](https://api.github.com/users/$){name}`);
return response.ok ? await response.json() : null;
})
)).map(({ value = null }) => value);
```