Welcome to this comprehensive guide on Promise.allSettled and Promise.all in Node.js! We'll be diving deep into these powerful tools, exploring their use cases, and providing practical examples to help you grasp these concepts. By the end of this tutorial, you'll be well-equipped to harness their potential in your projects. 🎯
Before we dive into Promise.allSettled and Promise.any, let's quickly recap on Promises. In Node.js, a Promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value. When a Promise is returned, you can attach callbacks (.then() and .catch()) to handle the resolved or rejected state, respectively. 📝
const promise = new Promise((resolve, reject) => {
// Asynchronous operation
// ...
if (/* success */) {
resolve('Result');
} else {
reject('Error');
}
});
promise
.then((result) => {
// Handle success
console.log(result); // 'Result'
})
.catch((error) => {
// Handle error
console.error(error); // 'Error'
});Promise.allSettled() takes an iterable of Promises and returns a single Promise that resolves to an array of objects, each representing the settled state (either resolved or rejected) of the corresponding input Promise. This function is particularly useful when you need to know the final outcome of multiple asynchronous operations, without relying on them all being resolved. 💡
const promise1 = new Promise((resolve, reject) => setTimeout(() => resolve('Result 1'), 1000));
const promise2 = new Promise((resolve, reject) => setTimeout(() => reject(new Error('Error 2')), 2000));
Promise.allSettled([promise1, promise2])
.then((results) => {
results.forEach(({ status, value }) => {
if (status === 'fulfilled') {
console.log(value); // 'Result 1'
} else {
console.error(value); // Error: Error 2
}
});
});Promise.any() works similarly to Promise.allSettled(), but it returns a single Promise that resolves with the first fulfilled value from the given iterable of Promises, or rejects with the reason of the first rejected Promise. This can be particularly useful when you're dealing with a group of Promises and are only interested in the first result, regardless of whether the others are fulfilled or rejected. 💡
const promise1 = new Promise((resolve, reject) => setTimeout(() => resolve('Result 1'), 1000));
const promise2 = new Promise((resolve, reject) => setTimeout(() => reject(new Error('Error 2')), 2000));
Promise.any([promise1, promise2])
.then((result) => {
console.log(result); // 'Result 1'
})
.catch((error) => {
console.error(error); // Error: Error 2
});What does `Promise.allSettled()` do?
That's it for this lesson! In the following sessions, we'll delve deeper into real-world examples, best practices, and advanced usage of Promise.allSettled and Promise.any. Stay tuned and happy learning! ✅