What is the usage of async in nodejs

WBOY
Release: 2022-01-10 11:15:07
Original
3676 people have browsed it

In nodejs, the async keyword can be used to define a function. When the async function is called, a Promise will be returned. When the async function returns a value, the Promise will be realized. When the function throws When an error occurs, the Promise is rejected.

What is the usage of async in nodejs

The operating environment of this tutorial: windows10 system, nodejs version 12.19.0, DELL G3 computer.

What is the usage of async in nodejs

1 What is the async function

Using the async function, you can use Asynchronous code with Promises is written just like synchronous code. Once you define a function using the async keyword, you can use the await keyword within the function. When an async function is called, it returns a Promise. When the async function returns a value, the Promise is fulfilled; if an error is thrown in the function, the Promise is rejected.

await keyword can be used to wait for a Promise to be resolved and return its realized value. If the value passed to await is not a Promise, it converts the value to a resolved Promise.

const rp = require('request-promise')
async function main () {
 const result = await rp('https://google.com')
 const twenty = await 20
 // 睡个1秒钟
 await new Promise (resolve => {
  setTimeout(resolve, 1000)
 })
 return result
}
main()
 .then(console.log)
 .catch(console.error)
Copy after login

2 Migrating to async functions

If your Node.js application is already using Promise, then you only need to rewrite the original chain call to await your Promise.

If your application is still using callback functions, you should gradually switch to using async functions. You can use this new technology when developing some new features. When you have to call some old code, you can simply wrap it into a Promise and call it in the new way.

To do this, you can use the built-in util.promisify method:

const util = require('util')
const {readFile} = require('fs')
const readFileAsync = util.promisify(readFile)
async function main () {
 const result = await readFileAsync('.gitignore')
 return result
}
main()
 .then(console.log)
 .catch(console.error)
Copy after login

3 Best practices for Async functions

3.1 Using async functions in express

express originally supports Promise, so it is relatively simple to use async functions in express:

const express = require('express')
const app = express()
app.get('/', async (request, response) => {
 // 在这里等待 Promise
 // 如果你只是在等待一个单独的 Promise,你其实可以直接将将它作为返回值返回,不需要使用 await 去等待。
 const result = await getContent()
 response.send(result)
})
app.listen(process.env.PORT)
Copy after login

But as Keith Smith pointed out, the above example has a serious problem - if The Promise is eventually rejected. Since there is no error handling here, the express route processor will be suspended.

To fix this problem, you should wrap your asynchronous handler in a function that handles errors:

const awaitHandlerFactory = (middleware) => {
 return async (req, res, next) => {
  try {
   await middleware(req, res, next)
  } catch (err) {
   next(err)
  }
 }
}
// 然后这样使用:
app.get('/', awaitHandlerFactory(async (request, response) => {
 const result = await getContent()
 response.send(result)
}))
Copy after login

3.2 Parallel execution

For example, if you are Write a program where an operation requires two inputs, one from the database and the other from an external service:

async function main () {
 const user = await Users.fetch(userId)
 const product = await Products.fetch(productId)
 await makePurchase(user, product)
}
Copy after login

What happens in this example?

Your code will first get the user,

then get the product,

and finally make the payment.

As you can see, since there is no interdependence between the first two steps, you can actually execute them in parallel. Here, you should use the Promise.all method:

async function main () {
 const [user, product] = await Promise.all([
  Users.fetch(userId),
  Products.fetch(productId)
 ])
 await makePurchase(user, product)
}
Copy after login

And sometimes, you only need the return value of the fastest resolved Promise - in this case, you can use the Promise.race method.

3.3 Error Handling

Consider the following example:

async function main () {
 await new Promise((resolve, reject) => {
  reject(new Error('error'))
 })
}
main()
 .then(console.log)
Copy after login

When executing this code, you will see a message similar to this:

(node:69738) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: error

(node:69738) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

In newer Node.js versions, if a Promise is rejected and not handled, the entire Node.js process will be Interrupt. Therefore, you should use try-catch when necessary: ​​

const util = require('util')
async function main () {
 try {
  await new Promise((resolve, reject) => {
   reject(new Error('
Copy after login

For more node-related knowledge, please visit: nodejs tutorial! !

The above is the detailed content of What is the usage of async in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!