Understand the new syntax of Async/Await in JavaScript
Inspired by the Zeit team blog post, our PayPal team recently migrated the server-side database to Async/Await. I want to share my experience with you.
First of all, let’s understand two terms:
- Async function
- Await keyword
You always talk about Async and Await together, but what you need to know is that they are two different things. What you need to understand about the Async function and the Await keyword is that they are certainly related to some extent, but the Async function can still be used without Await.
Related learning recommendations: javascript video tutorial
##The function will return a Promise
When you create a function using the async keyword, the function will always return a Promise. When you return inside an async function, it wraps your value with a Promise.// here is an async function async function getNumber() { return 4 // actually returns a Promise } // the same function using promises function getNumber() { return Promise.resolve(4) }
Async function and its Promise-based Equivalent
In addition to converting your return to a Promise, async functions have a The special thing is that it is the only place where you use the await keyword. Await allows you to pause the execution of an async function until it receives the result of a promise. This allows you to write async code that appears in the order of execution.// async function to show user data async function displayUserData() { let me = await fetch('/users/me') console.log(me) }// promise-based equivalent function displayUserData() { return fetch('/users/me').then(function(me) { console.log(me) }) })
Handling errors in Async functions
Because the async function is also a Promise, when you put an async function in the code, It will be absorbed and returned as a rejected Promise.// basic error handling with async functions async function getData(param) { if (isBad(param)) { throw new Error("this is a bad param") } // ... } // basic promise-based error handling example function getData(param) { if (isBad(param)) { return Promise.reject(new Error("this is a bad param")) } // ... }
try/catch, or you need to add a catch handler to the returned Promise.
// rely on try/catch around the awaited Promise async function doSomething() { try { let data = await getData() } catch (err) { console.error(err) } } // add a catch handlerfunction doSomething() { return getData().catch(err => { console.error(err) }) }
Integration
Make good use of the error handling properties of promise and the concise syntax of async functions, which can bring you some powerful capabilities. . In the simple example below, you will see how I took advantage of the error handling capabilities inherent in async functions, which allowed me to simplify the error handling process in my Express application.// catch any errors in the promise and either forward them to next(err) or ignore them const catchErrors = fn => (req, res, next) => fn(req, res, next).catch(next) const ignoreErrors = fn => (req, res, next) => fn(req, res, next).catch(() => next()) // wrap my routes in those helpers functions to get error handling app.get('/sendMoney/:amount', catchErrors(sendMoney)) // use our ignoreErrors helper to ignore any errors in the logging middleware app.get('/doSomethingElse', ignoreErrors(logSomething), doSomethingElse) // controller method can throw errors knowing router will pick it up export async function sendMoney(req, res, next) { if (!req.param.amount) { throw new Error('You need to provide an amount!') } await Money.sendPayment(amount) // no try/catch needed res.send(`You just sent ${amount}`)} // basic async logging middleware export async function logSomething(req, res, next) { // ... throw new Error('Something went wrong with your logging') // ... }
next(err) to handle errors. However, with
async/await, we can place errors anywhere in the code, and then the router will throw these errors to the next function provided by Express, which greatly simplifies error handling process.
The above is the detailed content of Understand the new syntax of Async/Await in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
