Promise API Static Methods
What it does: Built-in methods for handling multiple promises at once - like running them in parallel or racing them.
Promise.all() - “All or Nothing”:
Waits for ALL promises to succeed:
javascript
Promise.all([
fetch('/api/user'),
fetch('/api/posts'),
fetch('/api/comments')
]).then(results => {
// gets array: [userResponse, postsResponse, commentsResponse]
console.log("All requests done!");
}).catch(error => {
// if ANY promise fails, this runs immediately
console.log("Something failed:", error);
});Key Rule: One failure = whole thing fails immediately.
Promise.allSettled() - “Wait for Everyone”:
Waits for ALL promises, success or failure:
javascript
Promise.allSettled([
fetch('/api/user'),
fetch('/bad-url'), // this will fail
fetch('/api/posts')
]).then(results => {
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log("Success:", result.value);
} else {
console.log("Failed:", result.reason);
}
});
});
// Results: [{status: 'fulfilled', value: ...}, {status: 'rejected', reason: ...}, ...]Promise.race() - “First One Wins”:
Takes result from fastest promise (success OR failure):
javascript
Promise.race([
fetch('/api/fast'), // resolves in 100ms
fetch('/api/slow'), // resolves in 2000ms
fetch('/api/timeout') // rejects in 500ms
]).then(result => {
console.log("Winner:", result); // gets result from /api/fast
});Promise.any() - “First Success Wins”:
Takes first SUCCESS, ignores failures:
javascript
Promise.any([
fetch('/api/broken'), // fails fast
fetch('/api/slow'), // succeeds slow
fetch('/api/fast') // succeeds fast
]).then(result => {
console.log("First success:", result); // gets /api/fast or /api/slow
});Quick Creation Methods:
javascript
// Create resolved promise
Promise.resolve("data")
.then(data => console.log(data)); // "data"
// Create rejected promise
Promise.reject(new Error("failed"))
.catch(error => console.log(error)); // Error: failedInterview Gotchas:
javascript
// 1. Promise.all preserves order
Promise.all([
new Promise(resolve => setTimeout(() => resolve("slow"), 1000)),
new Promise(resolve => setTimeout(() => resolve("fast"), 100))
]).then(results => {
console.log(results); // ["slow", "fast"] - original order!
});
// 2. Non-promises get passed through
Promise.all([
Promise.resolve(1),
2, // not a promise
Promise.resolve(3)
]).then(results => {
console.log(results); // [1, 2, 3]
});
// 3. Empty array resolves immediately
Promise.all([]).then(() => console.log("Done!")); // runs immediatelyBottom line: Use Promise.all() when you need all results, Promise.allSettled() when you want to try everything, Promise.race() for fastest response, and Promise.any() for first success.
