Handling Promise rejection with a catch while using await in JavaScript


In JavaScript, users can perform particular actions using the Promise. For example, we can create the promise to fetch data from the database using the API. If the promise gets the data from the database successfully, that means the promise is a success, or the promise gets an error, which means the promise is rejected.

Let’s look at the syntax to create the promise first.

Syntax

Users can follow the syntax below to create a promise in JavaScript.

let testPromise = new Promise((res, rej) => {
   
   // perform some operation
});

In the above syntax, we have used the Promise() constructor with a ‘new’ keyword to create a promise.

Example

In the example below, we have created two different promises. Also, we have resolved and rejected them.

Users can see in the below code how we managed testPromise1 as it is successfully resolved. The logic part comes with the second promise that we need to use the catch block to handle the error. In the output, users can observe that the promise message for testPromise2 is printed from the catch block.

<html>
<body>
   <h2><i>Promise</i> in JavaScript</h2>
   <p id = "output"> </p>
   <script>
      let output = document.getElementById("output");
      
      // Creating the promise and resolving it
      let testPromise1 = new Promise((res, rej) => {
         res("The testPromise1 is resolved successfully!");
      });
      
      // rejecting the promise
      let testPromise2 = new Promise((res, rej) => {
         rej("The testPromise2 is Rejected due to error!");
      });
      
      // execute the testPromise1
      testPromise1.then((res) => {
         output.innerHTML += res;
         output.innerHTML += "</br>";
      });
      
      //execute the testPromise2, and use the catch block to handle errors.
      testPromise2
      .then((res) => {
         output.innerHTML += res;
      })
      .catch((error) => {
         output.innerHTML += "Inside the catch block for testPromise2. </br>";
         output.innerHTML += error;
      });
   </script>
</body>
</html>

Use Promise with asynchronous function and await keyword

Users have learned to create the promise. Also, learned to handle the resolved and rejected promises using the catch block.

Now, we will learn to use the promise with an asynchronous function and await keyword. So, we have to use the try-catch block to handle the errors from the rejected promise.

The asynchronous functions allow us to execute multiple tasks parallels in the program. We can define the function followed by the async keyword to make it asynchronous. After that, we can use the await keyword inside the function to wait for the promise result. Sometimes, without getting results from the promise, we can’t perform other tasks in the function. So, we have to wait for the results we can achieve using the await keyword.

Syntax

Users can follow the syntax below to use the try-catch block to handle promise errors when we use the promises with the await keyword.

async function executePromise() {
   try {
      
      // call the promise, and wait until it is fulfilled!
      await promise1();
   } catch (error) {
      
      // if the promise is rejected, control comes here
   }
}

In the above syntax, we have used the async keyword to make the function asynchronous and await keyword to wait until promises are fulfilled or rejected.

Example

In the example below, we have created the asynchronous function. Also, we have created the promise1() function, which returns a promise with rejection. In the asynchronous function, we have invoked the promise1() function with the await keyword, and control goes to the catch block as the promise is rejected.

<html>
<body>
   <h3>Handling the <i>Promise rejection using catch block</i> While using await keyword in JavaScript.</h3>
   <p id = "output"> </p>
   <script> 
      let output = document.getElementById("output");
      
      // rejecting the promise
      let Promise1 = () => {
         return new Promise((res, rej) => {
            rej(new Error(400));
         });
      };
      async function executePromise() {
         try {
            
            // call the promise, and wait until it is fulfilled!
            await Promise1();
         } catch (error) {
            output.innerHTML += "Promise is rejected, and an error message is " + error.message;
         }
      }
      executePromise();
   </script>
</body>
</html>

Example

In the example below, we have created the promise like same we have created in the above example, but we have added the timer in rejecting the promise.

When users click the “execute promise” button, it executes the executePromise() function. In the executePromise() function, we call the timerPromise() with await keyword, and the timerPromise() rejects the promise till 5 seconds, and until that function waits to move ahead.

<html>
<body>
   <h3>Handling the <i>Promise rejection using catch block</i> While using await keyword and timer in JavaScript. </h3>
   <p> Click on the "Execute promise" button and wiat for 5 seconds </p>
   <p id = "output"> </p>
   <button onClick = "executePromise()"> Execute promise </button>
   <script>
      let output = document.getElementById("output");
      
      // rejecting the promise
      let timerPromise = () => {
         return new Promise((res, rej) => {
            setTimeout(
               () => rej(new Error("Promise is rejected after 5 seconds")), 5000
            );
         });
      };
      async function executePromise() {
         try {
            
            // function will not move ahead until the promise is fulfilled.
            await timerPromise();
         } catch (error) {
            output.innerHTML += "Promise is rejected, and an error message is " + error.message;
         }
      }
   </script>
</body>
</html> 

In the above output, users can observe that when they click on the “Execute promise” button, after 5 seconds, they see an error message from the catch block as the promise takes 5 seconds for rejection.

Updated on: 10-Mar-2023

984 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements