Explain Promise.all with async-await in JavaScript?


Simple operations like adding two numbers or string manipulation codes execute sequentially in JavaScript and return the results instantly. But while coding for real−world applications, we frequently make time−taking calls to databases, APIs, and other applications. These longer calls don’t return the results instantly; they will rather return a promise.

A promise is an object to represent the future results of an asynchronous operation. It is used to handle asynchronous processes' eventual success or failure. For instance, if you request some object from an API in JavaScript, you will be given a promise that the task will eventually be complete or fail. After some time, you will get the result of the promise, whether it is fulfilled or rejected.

Promise.all()

  • Promise.all() is a method that takes multiple promises as input and returns a single promise.

  • Promises are efficient in handling the asynchronous nature of processes in JavaScript.

  • If all the input promises are fulfilled with no objection, then the result will be a single promise consisting of an array of result values from the inputted promises.

  • If any of the promises from the input is rejected, then we get an immediately rejected promise with the reason mentioned in the promise rejection. It doesn’t give us the results of remaining successful or resolved promises.

  • As the result of the promise is an iterable array, we can run loops and perform required operations accordingly.

Syntax

Users can use the following syntax to use Promise.all() in JavaScript.

Promise.all([promise1, promise2, promise3, ….])

Promise.all() accepts an array iterable as an input. The input array can take all promises or objects.

Async-await

The async keyword is used to declare an asynchronous function, and the “await” keyword can be used in the body of that function. The async and await keywords together show the asynchronous process behavior in a cleaner code.

In general, async functions will have any number of await statements or no await statements. async−await keywords give cleaner code compared to try−catch blocks. The async keyword makes the JavaScript function return a promise, and the “await” keyword is used to wait for a promise.

Syntax

async function function_name{
   let result = await (value);
   . . . . . . .
   . . . . . . .
}

We are now aware of promise.all() and async−await keywords. Let's look at the usage of async−await and promise.all() together in JavaScript.

Promise.all with async-await

The syntax for using the Promise.all method with async−await in JavaScript is as follows:

Syntax

The syntax for using the Promise.all method with async-await in JavaScript is as follows−

async function example() {
   try {
      const results = await Promise.all([promise1, promise2, ...]);
   } catch (error) {
      // handle error
   }
}

Here promise1, promise2, and so on are promises that you want to wait for. The Promise.all method returns a promise that is fulfilled with an array of the values of all the input promises, if all of the input promises are fulfilled. If any of the input promises are rejected, the Promise.all promise is rejected with the reason for the first promise that was rejected.

The async function example uses the try/catch statement to handle the error case, where the catch block is executed if any of the input promises are rejected.

Example 1

Let's take the case of social media platforms like Instagram. Certain actions can be performed on Instagram, including likes, comments, and shares. So, let's create three promises for operations like, comment and share. From the other functions, let's access these promises using promise.all() along with async and await keywords.

<html>
<body>
   <h2> Using the <i> Promise.all() </i> Method</h2>
   <p id="output"> </p>
   <script>
      let like_promise = () => {
         return new Promise((resolve, reject) => {
            resolve("Liked ");
         });
      };
      let comment_promise = () => {
         return new Promise((resolve, reject) => {
            resolve("commented ");
         });
      };
      let share_promise = () => {
         return new Promise((resolve, reject) => {
            resolve("shared ");
         });
      };
      let main_promise = async () => {
         let result = await Promise.all([like_promise(), comment_promise(), share_promise(), ]);
         document.getElementById("output").innerHTML = result
      };
      main_promise();
   </script>
</body>
</html>

Let's see an instance when a promise is rejected if we consider a scenario of blogs posting to a website. The three cases of posting are blog posts, blogs in progress, and blogs deleted. Let's reject the promise for the blog deleted case and observe the output.

The following are the steps to create this example in JavaScript.

  • Step 1 − Create a post function in JavaScript that should return a resolved promise.

  • Step 2 − Create a progress function in JavaScript that should also return an accepted promise.

  • Step 3 − Create a del function in JavaScript that rejects the promise when called.

  • Step 4 − Create an asynchronous function in JavaScript that waits for all promises through await keyword using promise.all(). When the function del is called from promise.all(), the output is an error with a rejection message as “post deleted”.

Example 2

<html>
   <h2> Using the Promise.all() Method with async-await</h2>
<body>
   <p id="output"> </p>
   <script>
      let post = () => {
         return new Promise((resolve, reject) => {
            resolve("blog posted");
         });
      };
      let progress = () => {
         return new Promise((resolve, reject) => {
            resolve("blog in progress");
         })
      };
      let del = () => {
         return new Promise((resolve, reject) => {
            reject("rejected promise");
         });
      };
      let blog_promise = async () => {
         try {
            let result = await Promise.all([progress(), post(), del()]);
            document.getElementById("output").innerHTML = result
         } catch (error) {
            document.getElementById("output").innerHTML = error
         }
      }
      blog_promise();
   </script>
</body>
</html>

We have learned working of promise.all() with async-await keywords in JavaScript. Along with their uses, two practical cases, one about all the promises being fulfilled and the other on the rejection of promises, are discussed in the tutorial.

Updated on: 29-Dec-2022

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements