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.
grammar
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.
Example
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 id="i-Promise-i-in-JavaScript"><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 functions and the await keyword
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.
grammar
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.
Example
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 id="Handling-the-i-Promise-rejection-using-catch-block-i-While-using-await-keyword-in-JavaScript">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 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 id="Handling-the-i-Promise-rejection-using-catch-block-i-While-using-await-keyword-and-timer-in-JavaScript">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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
