JavaScript Promise.all() Method
Execute multiple promises in parallel and handle their results efficiently
Introduction
Promise.all() is one of the most useful methods for handling multiple asynchronous operations in JavaScript. It allows you to run promises in parallel and wait for all of them to complete.
Syntax
Promise.all(iterable);
Parameters:
iterable: An iterable (usually an array) of Promise objects
Returns:
- A single Promise that resolves when all input promises resolve
- Rejects immediately if any input promise rejects
Basic Usage
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve) => {
setTimeout(resolve, 100, 'foo');
});
Promise.all([promise1, promise2, promise3]).then((values) => {
console.log(values); // [3, 42, 'foo']
});
Note: Non-promise values are treated as resolved promises.
Real-World Examples
Fetching Multiple Resources
async function fetchUserData(userId) {
const [user, posts, comments] = await Promise.all([
fetch(`/api/users/${userId}`),
fetch(`/api/users/${userId}/posts`),
fetch(`/api/users/${userId}/comments`),
]);
return {
user: await user.json(),
posts: await posts.json(),
comments: await comments.json(),
};
}
Parallel API Calls
async function getDashboardData() {
const [analytics, notifications, settings] = await Promise.all([
getAnalytics(),
getNotifications(),
getUserSettings(),
]);
return { analytics, notifications, settings };
}
Error Handling
Important: Promise.all() fails fast. If any promise rejects, the entire operation rejects immediately.
Promise.all([
Promise.resolve(1),
Promise.reject(new Error('Something failed')),
Promise.resolve(3),
]).catch((error) => {
console.error(error.message); // 'Something failed'
});
Handling Individual Errors
Use Promise.allSettled() if you need all promises to complete regardless of errors:
const results = await Promise.allSettled([
fetchUser(),
fetchPosts(),
fetchComments(),
]);
results.forEach((result) => {
if (result.status === 'fulfilled') {
console.log(result.value);
} else {
console.error(result.reason);
}
});
Performance Benefits
Promise.all() executes promises in parallel, not sequentially. This can significantly reduce total wait time.
// Sequential (slow)
const user = await fetchUser();
const posts = await fetchPosts();
const comments = await fetchComments();
// Total time: ~3000ms (if each takes 1000ms)
// Parallel (fast)
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments(),
]);
// Total time: ~1000ms
Common Pitfalls
Empty Array
Promise.all([]); // Resolves immediately with []
Non-Iterable
Promise.all(notAnIterable); // TypeError
Losing Error Context
Always add proper error handling to know which promise failed:
try {
await Promise.all([task1(), task2(), task3()]);
} catch (error) {
// Which task failed? Add context!
console.error('Batch operation failed:', error);
}
When to Use Promise.all()
✅ Good use cases:
- Independent operations that can run in parallel
- Need all results before proceeding
- Want to fail fast on any error
❌ Avoid when:
- Promises depend on each other (use chaining)
- Need individual error handling
- Working with infinite streams
Related Methods
Promise.allSettled()- Wait for all promises to settlePromise.race()- First promise to settle winsPromise.any()- First promise to fulfill wins
Conclusion
Promise.all() is essential for efficient parallel async operations. Master it to write faster, more responsive JavaScript applications.
#javascript #async #promises