What is Promise.all and when to use it
· Category: JavaScript
Short answer
Promise.all takes an iterable of Promises and returns a single Promise that resolves when all input Promises resolve, or rejects immediately if any reject.
How it works
- Resolves to an array of results in the same order as the input.
- Rejects with the first rejection reason, ignoring the rest.
Example
const [users, posts] = await Promise.all([
fetch("/users").then(r => r.json()),
fetch("/posts").then(r => r.json())
]);
When to use each
| Utility | Behavior |
|---|---|
Promise.all |
Fast fail on any rejection |
Promise.allSettled |
Wait for all, never rejects |
Promise.race |
Resolve/reject with the fastest |
Promise.any |
Resolve with first success, aggregate rejections |
Tips
- Wrap independent async calls in
Promise.allto run them in parallel. - Use
allSettledwhen you need to handle partial failures gracefully.
Common issues
- Passing non-Promise values works but is unnecessary; wrap them if unsure.
- A single rejection in
Promise.allcauses the whole operation to fail.