When a UI needs data from several sources, sending requests concurrently avoids waiting for each request to finish before starting the next. JavaScript promises let you combine those operations and handle their outcomes together. section 8.1.3
Choose a promise combinator based on how the results should be handled:
- Promise.all fulfills with values in input order when every promise fulfills; it rejects as soon as one rejects. section 8.1.3
- Promise.allSettled fulfills after every promise settles, reporting each outcome; Promise.any fulfills with the first fulfillment; Promise.race adopts the first settlement, fulfilled or rejected. section 8.1.3
Listing 8.4 Using Promise.all to combine multiple promises
const allPostsPromise = Promise.all( #A
[ #B
fetch("https://jsonplaceholder.typicode.com/posts/1"), #B
fetch("https://jsonplaceholder.typicode.com/posts/2"), #B
fetch("https://jsonplaceholder.typicode.com/posts/3"), #B
].map((fetchPromise) => #C
fetchPromise.then((response) => { #C
if (!response.ok) { #C
throw new Error(`Status code ${response.status}`); #C
} #C
return response.json(); #C
}), #C
), #C
);
allPostsPromise
.then((posts) => { #D
posts.forEach((post) => { #D
console.log(post); #D
}); #D
}) #D
.catch((reason) => { #E
console.error(`Request failed: ${reason}`); #E
}); #E
See multiple fetch requests combined with Promise.all, including response checks and shared error handling. section 8.1.3
Listing 8.5 Using Promise.race to enforce a timeout
const fetchController = new AbortController(); #A
const fetchPromise = fetch("https://httpbin.org/delay/2", { #B
signal: fetchController.signal, #B
}).then((response) => { #B
if (!response.ok) { #B
throw new Error(`Status code ${response.status}`); #B
} #B
return response.json(); #B
});
const timeoutPromise = new Promise((_, reject) => #C
setTimeout(() => { #C
fetchController.abort(); #C
reject(new Error("Request timeout"));
}, 1_000), #C
); #C
Promise.race([fetchPromise, timeoutPromise]) #D
.then((result) => {
console.log(result);
})
.catch((reason) => {
console.error(`Request failed: ${reason}`);
});
See Promise.race paired with AbortController to enforce a request timeout. section 8.1.3






























