diff --git a/5-network/01-fetch/01-fetch-users/solution.md b/5-network/01-fetch/01-fetch-users/solution.md index 3cb88e4ea5..97937cf780 100644 --- a/5-network/01-fetch/01-fetch-users/solution.md +++ b/5-network/01-fetch/01-fetch-users/solution.md @@ -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); +```