Home >Web Front-end >JS Tutorial >Handling Promise rejections with catch when using wait in JavaScript
In JavaScript, users can use Promise to perform specific operations. For example, we can create a Promise that uses an API to get data from a database. If the Promise successfully obtains data from the database, it means that the Promise is successful, otherwise if the Promise fails, it means that the Promise is rejected.
Let’s first look at the syntax for creating a Promise.
Users can create Promise in JavaScript according to the following syntax.
let testPromise = new Promise((res, rej) => { // perform some operation });
In the above syntax, we use the Promise() constructor with the "new" keyword to create a Promise.
In the following example, we create two different Promises. Furthermore, we have addressed and rejected them.
Users can see in the code below how we manage testPromise1 as it is resolved successfully. The logical part comes with the second promise that we need to use a catch block to handle errors. In the output, the user can observe that the Promise message of testPromise2 is printed out 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>
Users have learned to create promises. Additionally, you learned to use catch blocks to handle resolved and rejected promises.
Now, we will learn to use promises with asynchronous functions and the await keyword. Therefore, we have to use a try-catch block to handle errors in rejected Promise.
Asynchronous functions allow us to perform multiple tasks in parallel in the program. We can define a 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 the result from the Promise, we can't perform other tasks in the function. Therefore, we have to wait for the result which can be obtained using await keyword.
When we use promise with the await keyword, users can use the try-catch block to handle promise errors according to the following syntax.
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 use the async keyword to make the function asynchronous and the await keyword to wait for the Promise to be fulfilled or rejected.
In the example below, we create an asynchronous function. Additionally, we created the promise1() function, which returns a promise with a rejection. In the async function, we called the promise1() function using await keyword, and when the promise is rejected, control goes to the catch block.
<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>
In the example below, we create the same Promise that we created in the example above, but we add a timer when the Promise is rejected.
When the user clicks the "execute Promise" button, it will execute the executePromise() function. In the executePromise() function, we call timerPromise() using the await keyword, and timerPromise() rejects the promise until 5 seconds until the function wait continues go 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, the user can observe that when they click on the "Execute Promise" button, after 5 seconds, they see an error message from the catch block because the Promise takes 5 seconds to be rejected.
The above is the detailed content of Handling Promise rejections with catch when using wait in JavaScript. For more information, please follow other related articles on the PHP Chinese website!