Promises are a fundamental part of asynchronous programming in JavaScript, allowing developers to handle operations that may take time to complete, such as fetching data from an API. Two important methods provided by the Promise API are Promise.all() and Promise.race(). Understanding these methods is crucial for effectively managing multiple asynchronous operations.
The Promise.all() method takes an iterable of promises (usually an array) and returns a single promise that resolves when all of the promises in the iterable have resolved or rejects if any of the promises reject. This method is particularly useful when you need to perform multiple asynchronous operations in parallel and wait for all of them to complete before proceeding.
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);
});
Promise.all() will reject immediately, and the error will be caught in the catch block.Promise.allSettled() if you need to wait for all promises to settle (either resolve or reject) and want to handle each result individually.Promise.all() will return results in the order of the promises: The results will always be in the same order as the promises were passed in, regardless of the order in which they resolve.Promise.all() will reject, which may lead to unhandled promise rejections if not caught.In contrast, Promise.race() takes an iterable of promises and returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects. This method is useful when you want to take action based on the first promise that settles, regardless of whether it resolves or rejects.
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, 'First');
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(reject, 100, 'Second');
});
Promise.race([promise1, promise2])
.then(result => {
console.log('Resolved with:', result); // Output: 'Resolved with: First'
})
.catch(error => {
console.error('Rejected with:', error); // Output: 'Rejected with: Second'
});
Promise.race() for timeout scenarios: You can create a promise that rejects after a certain time and race it against other promises to implement timeouts.Promise.race() resolves or rejects based on the first promise that settles, ensure you handle both outcomes appropriately.Promise.race() will wait for all promises to settle; it only cares about the first one.In summary, both Promise.all() and Promise.race() serve distinct purposes in handling multiple asynchronous operations. By understanding their differences, best practices, and common pitfalls, developers can write more efficient and error-free asynchronous code.