FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

docs(fetch): add modern `Promise.allSettled` solution to fetch-users task by illia-m-b · Pull Request #3987 · javascript-tutorial/en.javascript.info · GitHub

Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .md  (1) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
15 changes: 15 additions & 0 deletions 5-network/01-fetch/01-fetch-users/solution.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
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);
```

Back | FazBrowse Home | New Git URL