Promise

https://medium.com/womenintechnology/callbacks-vs-promises-vs-async-await-detailed-comparison-d1f6ae7c778a#:~:text=Conclusion,and%20more%20readable%20code%20structures.

In JavaScript, Promise.all, Promise.race, Promise.any, and Promise.allSettled are methods used to handle multiple promises. Here’s a breakdown of each method and how they differ:

Promise.all

  • Description: This method takes an iterable (such as an array) of promises and returns a single promise that resolves when all of the promises in the iterable have resolved or rejects if any promise in the iterable rejects.
  • Usage:javascriptCopy codePromise.all([promise1, promise2, promise3]) .then(results => { // results is an array of the resolved values }) .catch(error => { // if any promise rejects, this block will execute });

Promise.race

  • Description: This method takes an iterable of promises and returns a single promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects.
  • Usage:javascriptCopy codePromise.race([promise1, promise2, promise3]) .then(result => { // result is the value of the first settled promise (resolved or rejected) }) .catch(error => { // if the first settled promise is rejected, this block will execute });

Promise.any

  • Description: This method takes an iterable of promises and returns a single promise that resolves as soon as any of the promises in the iterable resolves. If all promises reject, it rejects with an AggregateError, which is an error that groups multiple individual errors together.
  • Usage:javascriptCopy codePromise.any([promise1, promise2, promise3]) .then(result => { // result is the value of the first resolved promise }) .catch(error => { // if all promises are rejected, this block will execute // error is an AggregateError });

Promise.allSettled

  • Description: This method takes an iterable of promises and returns a single promise that resolves when all of the promises in the iterable have settled (either resolved or rejected). The returned promise resolves to an array of objects that each describe the outcome of each promise.
  • Usage:javascriptCopy codePromise.allSettled([promise1, promise2, promise3]) .then(results => { // results is an array of objects with each object having the following structure: // { status: "fulfilled", value: result } for resolved promises // { status: "rejected", reason: error } for rejected promises });

Summary:

  • Promise.all: Waits for all promises to resolve; rejects if any promise rejects.
  • Promise.race: Resolves or rejects as soon as one promise resolves or rejects.
  • Promise.any: Resolves as soon as one promise resolves; rejects only if all promises reject.
  • Promise.allSettled: Waits for all promises to settle (either resolve or reject); never rejects.

Leave a Comment