JavaScript provides these methods to manage multiple asynchronous operations.
✅ 1. Promise.all()
✔ Purpose:
Wait for ALL promises to succeed.
If ANY promise fails → the entire result fails.
✔ Best for:
- Fetching multiple API calls that all are required
- Loading dashboard data
- Running tasks in parallel
✔ Behavior:
- Returns array of results
- Rejects immediately if any promise rejects
Example:
Promise.all([
fetch("/user"),
fetch("/orders"),
fetch("/cart")
])
.then(res => console.log("All success"))
.catch(err => console.log("At least one failed"));
✅ 2. Promise.any()
✔ Purpose:
Returns the result of the first successful promise.
It ignores failures unless all fail.
✔ Best for:
- Fastest server response
- Fallback requests
- Multiple CDN URLs → take the first one that works
✔ Behavior:
- Resolves on first success
- Rejects only if ALL promises fail
Example:
Promise.any([
fetch("https://cdn1.com/file"),
fetch("https://cdn2.com/file"),
fetch("https://cdn3.com/file")
])
.then(res => console.log("First successful response"))
.catch(err => console.log("All failed"));
✅ 3. Promise.race()
✔ Purpose:
Returns the result of the first promise that settles
(doesn’t matter if it's resolved or rejected).
✔ Best for:
- Timeout or cancellation logic
- Taking the quickest operation (success or failure)
✔ Behavior:
- Whichever promise finishes first → resolve or reject immediately
Example:
const fetchData = fetch("/api/data");
const timeout = new Promise((_, reject) =>
setTimeout(() => reject("Timeout"), 2000)
);
Promise.race([fetchData, timeout])
.then(res => console.log("Completed first"))
.catch(err => console.log("First returned error:", err));
🔥 Summary Table
| Method | Resolves When | Rejects When | Use Case |
|---|---|---|---|
| Promise.all | All succeed | Any fails | Load multiple required APIs |
| Promise.any | First success | All fail | Fastest success, CDN fallback |
| Promise.race | First settles (success/fail) | First to settle is rejection | Timeout logic, speed competition |
🎯 Short Interview Answer
Promise.allwaits for all promises and fails if one fails.Promise.anyreturns the first successful promise and ignores failures unless all fail.Promise.racereturns the first promise that settles, whether success or failure.