In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Node.js asynchronous programming example analysis, I believe that many inexperienced people do not know what to do, so this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.
Overview of Asynchronous programming
In the former single-threaded model, due to the slow call of CPU O under the influence of synchronous Imax O, it can not be overlapped at the application level. In order to take care of the reading habits of programmers, synchronous Imax O has been popular for many years.
But there are big performance problems!
Node uses JavaScript and its internal asynchronous library to promote async directly to the business level. The most important feature brought by Node is the event-driven non-blocking IPUP O model. Non-blocking CPU O can make it possible for resources to be better utilized because they do not depend on each other.
Asynchronous programming solution
Purpose: to read the file contents corresponding to the main field in package.json
Callback
Use callback function to operate asynchronous Ibank O
Const fs = require ("fs"); fs.readFile (". / package.json", {encoding: "utf-8"}, (err, data) = > {if (err) throw err; const {main} = JSON.parse (data); fs.readFile (main, {encoding: "utf-8"}, (err, data) = > {if (err) throw err; console.log (data);}); copy code
Question: how to solve callback hell?
Promise
Promise is a finite state machine with four states, of which three core states are Pending, Fulfilled, Rejected, and an unstarted state
For more information, please see my previous blog post, Promise.
Use Promise to read the file contents corresponding to the main field in package.json
Const {readFile} = require ("fs/promises"); readFile (". / package.json", {encoding: "utf-8"}) .then (res) = > {return JSON.parse (res);}) .then (data) = > {return readFile (data.main, {encoding: "utf-8"});}) .then (res) = > {console.log (res);}); copy the code
Compared to the previous solution with Callback, you can see that there are no nested callbacks, handling asynchronous operations through a series of chained calls.
Callback to Promise
How to convert Callback to Promise form?
You can use the utility function util.promisify that comes with Node
You can do it yourself:
Function promisify (fn, receiver) {return (... args) = > {return new Promise ((resolve, reject) = > {fn.apply (receiver, [... args, (err, res) = > {return err? Reject (err): resolve (res);},]);});};} const readFilePromise = promisify (fs.readFile, fs); copy code
Await
The await function uses try catch to catch exceptions (note parallel processing)
Const {readFile} = require ("fs/promises"); const start = async () = > {const {main} = JSON.parse (await readFile (". / package.json", {encoding: "utf-8"})); const data = await readFile (main, {encoding: "utf-8"}); console.log (data);}; start (); copy code
The syntax of await is written like synchronous programming, where the operation is a serial operation that waits for execution line by line.
If several tasks can be done in parallel, it is not good to write in this way. This is, we can use Promise.all to operate parallel tasks.
There will also be a small question. I asked the teacher after class. This is the teacher's answer.
[Q] in the asynchronous part, when it comes to serial and parallel, I have a question in the parallel processing area. If the parallel scenario requires that each asynchronous task be completed regardless of the success or failure of other tasks, and finally handle errors uniformly, then when you use Promise.all to deal with multiple asynchronous tasks, you will return when you encounter the execution error of the first task. How can you make all the tasks complete, and then handle the error uniformly?
[answer] Promise.all handles multiple requests, and when all requests are successful, resolve returns an array containing the execution results. If a request fails, reject the error immediately, so we can't use Promise.all to implement this place. Promise has an allSettled method, developer.mozilla.org/en-US/docs/...
Event
Publish and subscribe mode, Node.js built-in events module
For example, HTTP server on ('request') event monitoring
Const EventEmitter = require ("events"); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter (); myEmitter.on ("event", () = > {console.log ("an event occurred!");}); myEmitter.emit ("event"); const http = require ("http"); const server = http.createServer ((req, res) = > {res.end ("hellograms! ); server.on ("request", (req, res) = > {console.log (req.url);}); server.listen (3000); copy code
After reading the above, have you mastered the method of sample analysis of asynchronous programming in Node.js? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
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.