Promise APIs (all, allSettled, race, any) + Interview Questions 🔥

Promise APIs (all, allSettled, race, any) + Interview Questions 🔥

In JavaScript, promises are a way to handle asynchronous operations. The methods Promise.all(), Promise.allSettled(), Promise.race(), and Promise.any() provide different ways to handle multiple promises. 

1. Promise.all()

Why Promise.all() is used?

Suppose, we have to make a parallel API call and get the result. It is used to handle multiple promises together

📌 CASE 1 -  All 3 promises are successful

Promise.all([p1, p2, p3])

  • it takes an array of promises as an input suppose we have 3 promises so prmise.all() make 3 API calls parallelly & get the result.
  • Assume P1 takes 3 sec, P2 takes 1 sec, P3 takes 2 sec.
  • it will take a total of 3 sec & wait for all of them to finish then it will collect the results and give the array as output [val1, val2, val3]


Code Example

const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("P1 Success");
  }, 3000);
});

const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("P2 Success");
  }, 1000);
});

const p3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("P3 Success");
  }, 2000);
});

Promise.all([p1, p2, p3]).then((results) => {
  console.log(results);  // ['P1 Success', 'P2 Success', 'P3 Success'] -> took 3 secs
});        


📌 CASE 2- If anyone's Promise get Rejected


Promise.all([p1, p2, p3])

  • assume P1 takes 3 sec, P2 takes 1 sec, P3 takes 2 sec.
  • If p2 gets rejected after 1 sec so it will Immediately throw an error & Promise.all() will be a failure.
  • It will not wait for other promises to either become success or failure. 


Conclusion

Promise.all() waits for all the input promises to resolve and returns a new promise that resolves to an array containing the results of the input promises. If one of the input promises is rejected, the Promise.all() method immediately returns a promise that is rejected with an error of the first rejected promise.


2. Promise.allSettled()


📌CASE 1- If all of them are successful

  • assume all 3 promises are successful.
  • Promise.allSettled will take 3secs and will give the promise value of result like [val1, val2, val3].
  • It will wait for all of them to finish then it will collect the results and give the array as output.


📌CASE 2- If anyone gets rejected


  • in the case of Promise.all([p1, p2, p3]). if p2 gets rejected after 1 sec
  • .Promise.allSettled will still wait for all promises to get settled first whether it is success or failure no matter & After 3 secs, it will give an array of output [val1, err2, val3].


CODE EXAMPLE

const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("P1 Success");
  }, 3000);
});

const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("P2 Success");
  }, 1000);
});

const p3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("P3 Fail");P2  }, 2000);
});

Promise.allSettled([p1, p2, p3])

  .then((results) => console.log(results))

  .catch((err) => console.error(err));        

Over here, it will wait for all promises to be either settled or rejected and then return, [ {status: 'fulfilled', value: 'P1 Success'}, {status: 'fulfilled', value: 'P2 Success'}, {status: 'rejected', reason: 'P3 Fail'} ]

3. Promise.race()

  • Promise.race([p1, p2, p3]) Assume P1 takes 3 sec, P2 takes 1 sec, P3 takes 2 sec.
  • It will give us the value of the first settled promise whether it is success or failure, it will give you the value of first settled promise.
  • Promise.race will give (val2) as output after 1sec as p2 got resolved at the earliest. Whereas if it would have been failed Promise.race would have still given output after 1 sec but this time with error.

4. Promise.any()

  • It is a success-seeking race 😂
  • It is very similar to the Promise.race() the only difference is Promise.race() waiting to be promise settled means success or rejected no matter.
  • In the case of Promise.any() as soon as our first promise gets resolved it returns a result of first resolved promise.
  • If in the above situation, p2 gets rejected, nothing will happen as Promise.any() seek for success, so the moment first success will happen that will become the result.
  • But what if all promises got failed, so the returned result will be an aggregated error i.e. [err1, err2, err3].


CODE EXAMPLE


📌CASE 1 wait for first settled success.


// 📌 First Scenario

const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('P1 Success');
  }, 3000);
});
const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('P2 Success');
  }, 5000);
});
const p3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject('P3 Fail');
  }, 2000);
});

Promise.any([p1, p2, p3])
  .then((results) => console.log(results))
  .catch(err => console.error(err));
        

It will wait for first settled **success**

In the above, p3 will be settled first, but since it is rejected, it will wait further & after 3 seconds it will print "P1 Success"

// 📌 Second Scenario

const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject('P1 Fail');
  }, 3000);
});
const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('P2 Success');
  }, 5000);
});
const p3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject('P3 Fail');
  }, 2000);
});

Promise.any([p1, p2, p3])
  .then((results) => console.log(results))
  .catch(err => console.error(err));

// After 5 secs: 'P2 Success'        

📌CASE 2 If all promises are rejected

  • Since all are rejected, so it will give "aggregate error" as output AggregateError:
  • All promises were rejected To get AggregateError array we need to write "err.errors"



const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject('P1 Fail');
  }, 3000);
});
const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject('P2 Fail');
  }, 5000);
});
const p3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject('P3 Fail');
  }, 2000);
});

Promise.any([p1, p2, p3])
  .then((results) => console.log(results))
  .catch(err => {
    console.error(err);
    console.error(err.errors); // ['P1 Fail', 'P2 Fail', 'P3 Fail']
  });
        

Summary

Promise.all(promises) – waits for all promises to resolve and returns an array of their results. If any of the given promises rejects, it becomes the error of Promise.all, and all other results are ignored.
Promise.allSettled(promises) (recently added method) – waits for all promises to settle and returns their results as an array of objects with: status: "fulfilled" or "rejected" value (if fulfilled) or reason (if rejected).
Promise.race(promises) – waits for the first promise to settle, and its result/error becomes the outcome.
Promise.any(promises) (recently added method) – waits for the first promise to fulfill, and its result becomes the outcome. If all of the given promises are rejected, AggregateError becomes the error of Promise.any.






To view or add a comment, sign in

More articles by Tejas Musale

  • async await 😍

    async await 😍

    Q: What is async? Ans - Async is a keyword used before a function to create an async function. Q: How is the async…

  • Creating a Promise, Chaining & Error Handling

    Creating a Promise, Chaining & Error Handling

    In the last post, we learned how to consume a promise. In this article, we will learn how to create our own promise…

  • Prmoises👫

    Prmoises👫

    Promises are used to handle async operations in JavaScript. Already learned in the previous post how things work before…

  • Asynchronous JavaScript & EVENT LOOP

    Asynchronous JavaScript & EVENT LOOP

    All JavaScript code runs on a call stack that executes quickly. The call stack does not wait for anything and executes…

  • Server-Driven UI vs. Configuration-Driven UI

    Server-Driven UI vs. Configuration-Driven UI

    In this article, we will embark on a journey to understand the fundamental differences between SDUI and CDUI, backed by…

    3 Comments
  • ReactJS: Understanding package.json and Package-lock.json.

    ReactJS: Understanding package.json and Package-lock.json.

    Hello everyone! In this article, we will understand package.json and Package-lock.

    4 Comments
  • CSS Variables with Global & Local Scope

    CSS Variables with Global & Local Scope

    Hello everyone! I've not posted anything about CSS yet. I am an aspiring Front-end Developer and suddenly realised I…

    1 Comment
  • Different Ways to Fetch Data in React Js?

    Different Ways to Fetch Data in React Js?

    Hi Everyone, In this blog, we’ll see how to fetch and display data using APIs and use it in a React app. There are…

    3 Comments
  • Understanding React Router and React Router V6: Some of the new changes

    Understanding React Router and React Router V6: Some of the new changes

    So not too long ago the library React Router updated to version 6 and with that, it came with some exciting changes so…

  • What is React Js? The Difference Between a Framework and a Library

    What is React Js? The Difference Between a Framework and a Library

    Hey everyone! I have been recently learning React js. My first question is whether React is a library or framework and…

Insights from the community

Others also viewed

Explore topics