All about Promise.all()  method in Javascript

All about Promise.all() method in Javascript

ยท

4 min read

Hi everyone ๐Ÿ‘‹ !! Hope you all are doing well. In this blog, I am going to discuss on Promise.all() method.

In simple words, Promises hold a value like a placeholder that's going to be available sometime later.

Promises are great when handling asynchronous operations. Javascript provides a method that handles multiple promises at once parallelly and gives the results in a single array.

What is Promise.all() ?

At first lets understand how we can run promises in a sequential flow.

Sequential flow of Promises

Lets create functions that return promises , its like a mock to an external API, where we need to wait a little until the response arrives. So we have three promises named as promise one , promiseTwo and promiseThree.

const promiseOne = () =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("promise one resolved");
    }, 600);
  });

const promiseTwo = () =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("promise two resolved");
    }, 300);
  });

  const promiseThree = () =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("promise three resolved");
    }, 100);
  });

So inorder to use them we gonna make async function fetchData.And then we call the function. As soon as we call the function we get the output as promise one resolved promise two resolved promise three resolved.

const fetchData = async () => {
  try{

    const responseOne = await promiseOne()
    const responseTwo = await promiseTwo()
    const responseThree = await promiseThree()

    console.log(responseOne ,responseTwo,responseThree)


  }catch(error){
    console.error("error",error)
  }
};
fetchData()
//promise one resolved promise two resolved promise three resolved

This is one way to do it but this is very inefficient because we are running this synchronously one after other.Lets add a timer to see how much time it takes.

const fetchData = async () => {
  try{
    console.time("timeSerial")
    const responseOne = await promiseOne()
    const responseTwo = await promiseTwo()
    const responseThree = await promiseThree()

    console.log(responseOne ,responseTwo,responseThree)
    console.timeEnd("timeSerial")

  }catch(error){
    console.error("error",error)
  }
};
fetchData()
//promise one ,promiseTwo and promiseThree
//timeSerial: 989.2000000001863ms

It takes approx 989 ms to resolve all the promises. You can check this CSB. Here we are creating a promiseOne and waiting for it to complete before we move to the next promiseTwo. Since we cannot run another promise before one is resolved, so the total execution time took about 9sec to complete all three promises i.e almost total time specified for all the promises.

Parallel flow of promises

But what if we can run all the promises at the same time and wait until all the promises resolves. Promise.all() method will help us to achieve this.

const fetchData = async () => {
  try {
      const allPromise = await Promise.all([
        promiseOne(),
        promiseTwo(),
        promiseThree()
    ]);

    console.log(allPromise);

  } catch (error) {
    console.error("error", error);
  }
};
fetchData();
//["promise one resolved", "promise two resolved", "promise three resolved"]

Now lets see how much time it takes to call the promises.

const fetchData = async () => {
  try {
      console.time("timeParallel")
      const allPromise = await Promise.all([
        promiseOne(),
        promiseTwo(),
        promiseThree()
    ]);
    console.timeEnd("timeParallel")

    console.log(allPromise);

  } catch (error) {
    console.error("error", error);
  }
};
fetchData();

//timeParallel: 593.7999999998137ms 
//["promise one resolved", "promise two resolved", "promise three resolved"]

So the total execution time is about 593ms . Since all the promises started at the same time the total execution time is the time of the longest promise to get resolved .In our case promiseOne has the longest timer of 600ms. Note that promises start their task when they are being created. Promise.all just waits until all the given promises are resolved.

So Promise.all() method takes an array of promises and returns a single promise that resolves to an array of the results of the input promises.

Promise.all() { if one promise rejects }

But what happens if one of the promise gets rejected ?

In our code lets see what happens when promiseTwo gets rejected .

const promiseOne = () =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("promise one resolved");
    }, 600);
  });

const promiseTwo = () =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      reject("promise two rejected");
    }, 300);
  });

const promiseThree = () =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("promise three resolved");
    }, 100);
  });
const fetchData = async () => {
  try {
         const allPromise = await Promise.all([
        promiseOne(),
        promiseTwo(),
        promiseThree()
    ]);

    console.log(allPromise);

  } catch (error) {
    console.error("error", error);
  }
};
fetchData();

//error promise two rejected

Here we will see that as soon as promise.all() finds a rejected input promise it rejects with an error .This makes allPromise reject right away even if promiseThree has been fulfilled. So we can conclude with these that if at least one promise in the promises array rejects, then the promise results with an error .

When should we use Promise.all() method?

  • When we need successful results of all the promises.

  • When our code relies on multiple related asynchronous tasks to work correctly. So instead of running these tasks serially, run them parallelly and wait for their execution with a single Promise.all.

This comes to the end of the blog. Hope you folks find it useful. Any suggestions or anything to add I would love to hear it in the comments below.Thank youโœจ !!

๐Ÿ‘‰Connect with me: Linkedin Twitter

ย