Promises.all() in JavaScript
🧵 What is Promise.all()?
Promise.all() is a method that takes an array of promises and returns a single promise that resolves when all the promises in the array resolve, or rejects if any one promise rejects.
>>“It’s perfect for running multiple async operations in parallel and waiting for all of them to finish.”
📦 Syntax
Code Snippet
Promise.all([promise1, promise2, promise3])
.then((results) => {
// All resolved values in an array
})
.catch((error) => {
// First rejection reason
});🚀 Example: Parallel Requests
Multiple Async Tasks
const p1 = Promise.resolve(1);
const p2 = new Promise((resolve) => setTimeout(() => resolve(2), 1000));
const p3 = new Promise((resolve) => setTimeout(() => resolve(3), 2000));
Promise.all([p1, p2, p3])
.then((values) => {
console.log(values); // [1, 2, 3]
});Note
🧠 The order of results matches the original array, not the completion order.
⛔ If One Promise Fails
Reject Scenario
const success = Promise.resolve("✅ Success");
const fail = Promise.reject("❌ Failed");
Promise.all([success, fail])
.then((values) => {
console.log("Won't run");
})
.catch((error) => {
console.error(error); // ❌ Failed
});Note
❗ The moment any promise rejects, Promise.all() rejects immediately.
🔄 Use Case: Fetching Multiple APIs
Multiple Fetch Requests
const urls = [
"https://jsonplaceholder.typicode.com/users/1",
"https://jsonplaceholder.typicode.com/posts/1",
"https://jsonplaceholder.typicode.com/comments/1"
];
const fetchAll = urls.map((url) => fetch(url).then((res) => res.json()));
Promise.all(fetchAll)
.then(([user, post, comment]) => {
console.log("User:", user);
console.log("Post:", post);
console.log("Comment:", comment);
})
.catch((error) => {
console.error("One of the fetches failed:", error);
});📌 Key Notes
- It waits for all promises to resolve.
- If any promise fails, the whole operation fails.
- Great for parallel operations like loading data, images, etc.
📖 Related Methods
- Promise.allSettled() – Waits for all to finish, regardless of success or failure.
- Promise.race() – Resolves/rejects as soon as one settles.
- Promise.any() – Resolves when any one resolves (ignores rejections unless all fail).
🔗 More on Promises
>>“Use Promise.all() when everything must succeed. Fail fast if any fail.”