Promises have become an integral part of asynchronous JavaScript, offering elegant ways to handle multiple asynchronous operations. Today, let's unravel the mysteries of Promise.all
and Promise.allSettled
.
The first: Promise.all
Consider a scenario where you have multiple promises, and you want to know when they all fulfill successfully. Enter Promise.all
. This method takes an array of promises and returns a new promise that fulfills with an array of results when all input promises have fulfilled. If any promise rejects, the entire operation is rejected.
Example:
const promise1 = Promise.resolve('One');
const promise2 = Promise.resolve('Two');
const promise3 = Promise.resolve('Three');
Promise.all([promise1, promise2, promise3])
.then(values => console.log(values))
.catch(error => console.error(error));
/*
In this example, the then block logs ['One', 'Two', 'Three'] since all promises fulfill successfully.
*/
The second: Promise.allSettled
Now, what if you want to know the outcome of every promise, regardless of whether it fulfills or rejects? That's where Promise.allSettled
shines. This method also takes an array of promises but doesn't short-circuit on the first rejection. Instead, it waits for all promises to settle (fulfill or reject) and then provides an array of result objects.
Example:
const promise1 = Promise.resolve('One');
const promise2 = Promise.reject('Two failed');
const promise3 = Promise.resolve('Three');
Promise.allSettled([promise1, promise2, promise3])
.then(results => console.log(results))
.catch(error => console.error(error));
/* In this example, the then block logs an array of result objects:
[
{ status: 'fulfilled', value: 'One' },
{ status: 'rejected', reason: 'Two failed' },
{ status: 'fulfilled', value: 'Three' }
]
*/
In summary, Promise.all
is your go-to for a race scenario where all promises must fulfill successfully, while Promise.allSettled
is your ally when you want to gracefully handle both fulfillment and rejection, providing insights into every promise's outcome.
Next time you're juggling multiple promises, choose the tool that aligns with your desired behavior.
Console You Later!
Top comments (0)