Understanding how Promise.all works is essential for managing asynchronous operations in JavaScript effectively. It allows you to execute multiple promises in parallel and wait for all of them to resolve or for any of them to reject. This method is particularly useful when you need to perform several asynchronous tasks simultaneously, such as fetching data from multiple APIs.
Promise.all takes an iterable of promises as an argument and returns a single promise that resolves when all of the promises in the iterable have resolved. If any of the promises reject, the returned promise immediately rejects with the reason of the first promise that rejected.
Here’s a simple example of how Promise.all can be used:
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(resolve, 100, 'foo'));
const promise3 = 42;
Promise.all([promise1, promise2, promise3])
.then(values => {
console.log(values); // Output: [3, 'foo', 42]
})
.catch(error => {
console.error('One of the promises failed:', error);
});
Here’s a practical example using the Fetch API to retrieve data from multiple endpoints:
const fetchUserData = (userId) => {
return fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then(response => response.json());
};
const fetchPostsData = (userId) => {
return fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`)
.then(response => response.json());
};
const userId = 1;
Promise.all([fetchUserData(userId), fetchPostsData(userId)])
.then(([userData, postsData]) => {
console.log('User Data:', userData);
console.log('Posts Data:', postsData);
})
.catch(error => {
console.error('Error fetching data:', error);
});
In this example, we fetch user data and posts data concurrently. If either fetch fails, the error will be caught in the catch block, allowing for better error management.