How to use Promise.all with Async & Await

Today we are going to discuss How to use promise.all with Async & Await so let’s start with promise.all function.

Promise.all Function

Promise.all() is an inbuilt function in Javascript it is used to handle multiple promise functions because declaring more than one promise function can make your code file so messy and difficult to understand and read as well.

A simple promise function consists of 4 statements (resolve, reject, then and catch) which make the code confusing and lengthy.

It returns the output of all promise functions in a single array, You can use promise.all()  function for executing all the promise functions in a single function.

You wouldn’t need to declare then and catch statements multiple times we can declare it once in promise.all() function, instead of executing each promise individually.

In the promise.all() function if one of the promises got rejected or did not compile successfully so the rest of the promises will also be not compiled.

Syntax

Promise.all([ first_promise , second_promise, .......])

Async & Await

Javascript introduced the async/await method in ECMAScript 2017 for dealing with promise functions easily.

The async method returns a promise by itself in output, the async method makes the code easy to understand and short.

Await is used in the scenario where we want to bring the user data. Await holds the function command execution until the complete data is fetched.  

Syntax

let method = async () => {

let result = await (value);
    .....
}

Promise.all With Async & Await Examples

Example 1


// Defining promise1

let Promise1 = () => { return new Promise((resolve, reject) => {
               
resolve("Hello World! ");

});
};

// Defining promise2

let Promise2 = () => {

return new Promise((resolve, reject) => {  resolve("Hi Universe ");

});
};

// declaring Async function to perform execution of all promises

let promisecompilation = async () => {

let promise = await Promise.all([

               Promise1(),

               Promise2(),
]);

console.log(promise);

};

// calling function

promisecompilation();

In the above example, we declared two promise functions then we created an async function for executing both promise functions asynchronously.

In the next step, we used promise.all() function with await statement, it will pause the execution until both promise functions are compiled successfully.

In the end, we printed the promise in the console and called the promisecompilation() function.

Output

Example 2

const fetchUsers = () => {

  return new Promise((resolve, reject) => {

    return setTimeout( () => resolve([{ id: 'Alex' }, { id: 'Tony' }, { id: 'Peter' }]),
  
    400

    )

  })

}


// Second promise depends on the output of first promise

const fetchUsersId = (user) => {

  return new Promise((resolve, reject) => {

    return setTimeout(() => resolve(user.id), 300)

  })

}


// Third promise depends on the output of the second promise

const UppercaseIds = (id) => {

  return new Promise((resolve, reject) => {

    return setTimeout(() => resolve(id.toUpperCase()), 200)

  })

}

const exeAsyncFunctions = async () => {

  const users = await fetchUsers()

  Promise.all( users.map(async (user) => {
      
const userId = await fetchUsersId(user)
     
console.log(userId)

      const capitalizedId = await UppercaseIds(userId)
     
console.log(capitalizedId)

    })

  )

  console.log(users)

}

exeAsyncFunctions()


In the above example, we created three promise functions, the first promise will fetch users from the array we declared.

The second promise will fetch user Ids and the third promise will convert them into uppercase.

The next step we declared async and await statements for fetching all users, the next promise will not execute until all users are fetched.

Then we used promises.all() methods for executing all declared promise functions.   

Output

Example 3

let Promise1 = () => {

  return new Promise((resolve, reject) => {
   
resolve("Hello World! ");

  });

};

// Defineng second promise

let Promise2 = () => { 

 return new Promise((resolve, reject) => {
   
reject("failed");

  });

};

// Defining third promise

let Promise3 = () => {

  return new Promise((resolve, reject) => {

    return setTimeout(() => {

      resolve("Hi Universe");

    }, 2000);

  });

};

// Async function to perform execution of all promise

let proExecution = async () => {

  let promise = await Promise.all([

    Promise1(),

    Promise2(),

    Promise3(),

  ]);
 
console.log(promise);

};

// calling function

proExecution();

In the above example, we simply declared three promises and we rejected the second one.

Output

As you can see it is showing an error, as we mentioned above if a promise got rejected from multiple promise functions so rest of the promises will also be not compiled.

Conclusion

In this tutorial, we discussed what is promise.all() function and how it works, then we discussed async and await statements and their working with promise.all() method.

We practice some examples using async and await statements with the promise.all() method.

Hope you like the tutorial if you have any queries related to this article feel free to ask below.

Suggested Article:

Leave a Comment