What is promise.all
Promise.all() is a built-in JavaScript method used to handle multiple asynchronous operations together. It accepts an iterable of promises (usually an array) and returns a single promise that resolves only when all the input promises have successfully resolved.
If any one of the promises rejects, the whole Promise.all() call rejects immediately and the error is passed to the .catch() block. The result array contains values in the same order as the input promises, even if they finish at different times.
const fetchUser = () => Promise.resolve({ id: 1, name: "John" });
const fetchOrders = () =>
new Promise((resolve) => setTimeout(() => resolve([101, 102]), 200));
const fetchProfile = () => Promise.resolve("active");
Promise.all([fetchUser(), fetchOrders(), fetchProfile()])
.then(([user, orders, status]) => {
console.log(user); // { id: 1, name: 'John' }
console.log(orders); // [101, 102]
console.log(status); // 'active'
})
.catch((error) => {
console.log("One of the requests failed:", error);
});
Let's consider a case where one promise rejects:
Promise.all([
Promise.resolve("A"),
Promise.reject(new Error("Request failed")),
Promise.resolve("C"),
])
.then((values) => console.log(values))
.catch((error) => console.log(error.message)); // Request failed
Key points:
- It waits for all promises to resolve.
- It rejects as soon as any promise fails.
- The output order matches the input order, not the completion order.
- Non-promise values are treated as resolved values automatically.
Promise.all() is useful when you need to run multiple independent async tasks concurrently and continue only after all of them are done, such as fetching multiple API endpoints together.