In this article, we will try to understand how we may handle Promise’s rejection with a try/catch block while using await inside an asynchronous (having prefix as an async keyword) function (or a method).
Syntax: Let us first quickly visualize the following illustrated syntax which we may use to create a Promise in JavaScript:
let new_promise = new Promise ((resolve, reject) => { // do something.... })
Let us see a quick example that will illustrate how to use the above-mentioned syntax for creating a promise:
Example 1: In this example, we will simply create a promise which will be resolved successfully containing data that will be printed out as output or result.
JavaScript
< script > let new_promise = new Promise((resolve, reject) => { resolve("neveropen....!!"); }); console.log("Promise created: " + new_promise); new_promise.then((result) => console.log( "Data inside promise is : " + result)); </ script > |
Output:
Promise created: [object Promise] Data inside promise is : neveropen....!!
Now after analyzing the promise’s syntax through an example let us have a look at the below-mentioned example which will help us to understand our problem statement in an efficient manner.
Example 2: In this example, we will create a promise inside a function (or a method) and further we will make that promise as rejected (under reject() state method) and in another function (or method) we will call that method under try block and further we will catch the error inside the catch() block itself.
JavaScript
< script > function rejected_promise() { return new Promise((resolve, reject) => { reject(new Error( "This promise is Rejected...")); }); } async function displayData() { try { await rejected_promise(); } catch (e) { console.log("Error Message: ", e.message); } } displayData(); </ script > |
Output:
Error Message: This promise is Rejected...
Example 3: In this example, we will create a rejected promise inside a function and while creating the promise we will use a timer function called setTimeout() and inside that setTimeout() function we will pass in our reject() method and then in another function, we will create a try/catch block and then we will print our result.
JavaScript
< script > function rejected_promise() { return new Promise((resolve, reject) => { setTimeout(() => { reject(new Error( "This Promise is Rejected...")); }, 1000); }); } async function displayData() { try { await rejected_promise(); } catch (error) { console.log("Error Message: ", error.message); } } displayData(); </ script > |
Output:
Error Message: This Promise is Rejected...