Promise.all Success Case
You'll learn how Promise.all() returns results when all promises succeed.
The Core Idea
When you pass an array of promises to Promise.all(), it waits for every single promise to resolve successfully. Once they all settle successfully, Promise.all() returns a single promise that resolves to an array containing all the results—in the exact same order as the input promises, regardless of which promise finished first.
Order Preservation is Key
Think of Promise.all() like organizing a group photo: even if person #3 arrives first and person #1 arrives last, they still stand in their assigned positions (1, 2, 3) for the picture. The timing of completion doesn't matter; the order of results matches the order you requested them.
const promise1 = Promise.resolve(10);
const promise2 = new Promise(resolve => setTimeout(() => resolve(20), 100));
const promise3 = Promise.resolve(30);
Promise.all([promise1, promise2, promise3])
.then(results => {
console.log(results); // [10, 20, 30]
// Always in order: promise1, promise2, promise3
// Even though promise2 took longer!
});
Accessing Individual Results
Because the result is an array in predictable order, you can destructure or index into it confidently:
Promise.all([fetchUser(), fetchPosts(), fetchComments()])
.then(([user, posts, comments]) => {
// user corresponds to fetchUser()
// posts corresponds to fetchPosts()
// comments corresponds to fetchComments()
console.log(`User: ${user.name}, Posts: ${posts.length}`);
});
Key Takeaway: Promise.all() resolves to an array of results in the same order as the input promises, making it predictable and easy to work with when all operations succeed.