Home > Web Front-end > JS Tutorial > body text

Let's talk about how to use async functions in Node.js

青灯夜游
Release: 2023-01-10 20:29:01
forward
1923 people have browsed it

Let's talk about how to use async functions in Node.js

With the new version of V8 engine, Node.js supports async function features starting from 7.6. On October 31 this year, Node.js 8 also became a new long-term support version, so you can use async functions in your code with confidence. In this article, I will briefly introduce what async functions are and how they can change the way we write Node.js applications.

What is async function

Using async function, you can write Promise-based asynchronous code 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. [Related tutorial recommendations: nodejs video tutorial, Programming teaching]

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

Migrating to async functions

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

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

Best Practices for Async Functions

Use async functions in express

express originally supports Promise, so using async functions in express is relatively simple:

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, above There is a serious problem with this example - if the Promise is ultimately rejected, since there is no error handling here, the express route handler will hang.

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

Parallel execution

For example, you are writing 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

In this example, what will happen?

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.

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

The above is the detailed content of Let's talk about how to use async functions in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.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