1. Promise.all: When You Need Them All
Imagine you have a bunch of Promises, and you need all of them to resolve before proceeding. Promise.all comes to the rescue! It ensures that all Promises resolve successfully, or none at all. Perfect for parallel tasks.
const promises = [promise1, promise2, promise3];
Promise.all(promises)
.then((results) => {
// All Promises resolved successfully!
})
.catch((error) => {
// Handle any error that occurred.
});
2. Promise.allSettled: Unconditional Vigilance
What if you need to know the status of each Promise, regardless of whether it resolves or rejects? Enter Promise.allSettled. It keeps you informed about every Promise's fate, making it invaluable for error handling. ๐
const promises = [promise1, promise2, promise3];
Promise.allSettled(promises)
.then((results) => {
// Array of objects describing the state of each Promise.
});
3. Promise.race: The Fast and the Furious
Speed matters. Sometimes, you just need the first Promise to resolve or reject. Promise.race is your go-to choice. It's like a race between Promises, and the first one to finish wins. ๐
const promises = [promise1, promise2, promise3];
Promise.race(promises)
.then((result) => {
// The first Promise to resolve or reject.
});
4. Promise.any: The Optimist's Choice
When you're hopeful that at least one Promise will resolve successfully, turn to Promise.any. It resolves as soon as the first Promise fulfills, making it ideal for scenarios where you want the best outcome. ๐
const promises = [promise1, promise2, promise3];
Promise.any(promises)
.then((result) => {
// The first Promise to resolve successfully.
})
.catch((errors) => {
// All Promises rejected.
});