Fetch combined with Promise All
Each call to fetch() returns a promise, so Promise.all() can wait for several requests at once. The requests run in parallel, which is much quicker than making each one wait for the one before when they do not depend on each other.
The examples request sample data from JSONPlaceholder, as on the Promises - Fetch Method page.
Two requests, one result
Section titled “Two requests, one result”A small getJson() helper keeps each request to one call. It checks the status, because fetch() does not reject on an error status, and it returns the promise from json(), so each promise it returns is fulfilled with the parsed body:
const base = 'https://jsonplaceholder.typicode.com';
const getJson = (url) => fetch(url).then((response) => { if (!response.ok) { throw new Error(`${response.status} from ${url}`); } return response.json(); });
Promise.all([getJson(`${base}/users/2`), getJson(`${base}/todos?userId=2`)]) .then(([user, todos]) => { const open = todos.filter((todo) => !todo.completed).length; console.log(`${user.name} has ${open} of ${todos.length} to-dos still open`); }) .catch((error) => console.log('Failed:', error.message));This prints:
Ervin Howell has 12 of 20 to-dos still openReading the bodies takes a second wait
Section titled “Reading the bodies takes a second wait”Without a helper, Promise.all() gives an array of Response objects, and calling json() on each gives an array of new promises rather than data. A second Promise.all() waits for those:
const base = 'https://jsonplaceholder.typicode.com';const ids = [1, 2, 3];
Promise.all(ids.map((id) => fetch(`${base}/users/${id}`))) .then((responses) => Promise.all(responses.map((response) => response.json()))) .then((users) => users.forEach((user) => console.log(user.id, user.email)));This prints:
1 Sincere@april.biz2 Shanna@melissa.tv3 Nathan@yesenia.netThis version skips the status check for brevity, so an error page would reach json() and fail there. The helper in the first example is the safer pattern.
Keeping the requests that worked
Section titled “Keeping the requests that worked”Promise.all() is rejected as soon as one request fails, which discards the others. When each result is useful on its own, Promise.allSettled() keeps them. Here the user with id 99 does not exist:
const urls = [`${base}/users/1`, `${base}/users/99`, `${base}/users/3`];
Promise.allSettled(urls.map(getJson)).then((results) => { results.forEach((result) => { if (result.status === 'fulfilled') { console.log('Loaded', result.value.name); } else { console.log('Skipped:', result.reason.message); } });});This prints:
Loaded Leanne GrahamSkipped: 404 from https://jsonplaceholder.typicode.com/users/99Loaded Clementine BauchThis example uses the base and getJson() from the first example. Starting many requests at once can overload a server, so for long lists of URLs it is worth sending them in batches.
Steve Griffith covers this topic in his video Combining fetch and the Promise all Method.