Promise.all(), Promise.race() & Promise.allSettled

CodeyMaze
2 min readMar 15, 2022

--

Promise.all(). Promise.race() & Promise.allSettled are the static methods. These can be used if we need to call multiple promises all at once.

Promise.all()

Promise.all() is a static method. If we want to execute many promises in parallel, then we can use Promise.all() method. This method accepts an array of promises and returns a promise if :

  1. All Promises that are passed in the array gets resolved.
  2. If any one promise from the passed array gets rejected.

Let’s take an example of using Promise.all() :

Output of the above would be :

First Promise gets resolved

Second Promise gets resolved

Third Promise gets resolved

Promise.race()

Promise.race() also accepts a list of promises that need to be executed in parallel but it returns the first settled promise. Settled means either the promise gets fulfilled or rejected. It is like a race of promises out of all promises which promise settles first.

The output of the above will be :

Second Promise Resolved

In this case, the second promise gets resolved before the first because the time duration is 1000 which is less than 3000. so the second promise gets returned — it wins the race.

Promise.allSettled()

Promise.allSettled also accepts an array of promises but it waits for all promises to settle and returns their results with status and value.

Status fulfilled if the promise resolves and rejected if the promise rejects.

Value in case of promise resolved and reason in case of promise rejects.

The output of the above would be :

[{ status: “fulfilled”, value: “My First Promise Resolved” }, { reason: “My Second Promise Rejected”, status: “rejected” }]

Promise.allSettled() method is going to run all promises and returns their results whatever it is — resolves or rejects.

Subscribe to our Youtube channel for more videos :

https://www.youtube.com/channel/UCEXWe9R6-ppk4zhNo2JbtmQ

--

--

CodeyMaze
CodeyMaze

Written by CodeyMaze

Crafting Solutions Through Code & Words https://codeymaze.com Feel free to follow me :)

No responses yet