In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Today, the editor will share with you the relevant knowledge about how to use async in nodejs. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
In nodejs, the async keyword can be used to define a function. When the async function is called, it returns a Promise, when the async function returns a value, the Promise is implemented, and when the function throws an error, the Promise is rejected.
This tutorial operating environment: windows10 system, nodejs version 12.19.0, DELL G3 computer.
What is the use of async in nodejs
1 what is an async function
With the async function, you can write Promise-based asynchronous code just like synchronous code. Once you have defined a function using the async keyword, you can use the await keyword within that function. When an async function is called, it returns a Promise. When the async function returns a value, that Promise is implemented; if an error is thrown in the function, the Promise is rejected.
The await keyword can be used to wait for a Promise to be resolved and return its implemented 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 / / sleep for 1 second await new Promise (resolve = > {setTimeout (resolve, 1000)}) return result} main () .then (console.log) .catch (console.error)
2 transfer to async function
If your Node.js application is already using Promise, you only need to rewrite the original chained calls to await your Promise.
If your application is still using callbacks, you should switch to the async function in an incremental manner. You can use this new technology when developing some new features. When you have to call some old code, you can simply wrap it as a Promise and call it in a 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)
3 Best practices for Async functions
3.1 use the async function in express
Express already supports Promise, so using the async function in express is relatively simple:
Const express = require ('express') const app = express () app.get (' /', async (request, response) = > {/ / wait here for Promise / / if you are just waiting for a separate Promise, you can actually return it as a return value without using await to wait. Const result = await getContent () response.send (result)}) app.listen (process.env.PORT)
But as Keith Smith points out, there is a serious problem with the above example-if Promise is eventually rejected, the express routing processor will hang because there is no error handling here.
To fix this, you should wrap your asynchronous processor in a function that handles errors:
Const awaitHandlerFactory = (middleware) = > {return async (req, res, next) = > {try {await middleware (req, res, next)} catch (err) {next (err)} / / then use app.get ('/', awaitHandlerFactory (async (request, response) = > {const result = await getContent () response.send (result)})
3.2 parallel execution
For example, you are writing a program where an operation requires two inputs, one from a 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)}
What happens in this case?
Your code will first get the user.
Then get the product
Finally, payment will be made.
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)}
Sometimes, you only need the return value of the Promise that is resolved most quickly-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)
When you execute this code, you will see a message like 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 versions of Node.js, if Promise is rejected and not processed, the entire Node.js process is interrupted. So you should use try-catch if necessary:
Const util = require ('util') async function main () {try {await new Promise ((resolve, reject) = > {reject (new Error (' above is all the content of this article "how to use async in nodejs", thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.