In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
How to achieve the event cycle in nodejs, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
Process.nextTick
Process.nextTick () is not executed in any phase of event loop, but in the middle of each phase switch; that is, before switching from one phase to the next
There are three ways to define asynchronous events: setTimeout,setImmediate,process.nextTick ()
Var fs = require ('fs') Fs.readFile (_ _ dirname () = > {setTimeout (()) = > {console.log ('setTimeout')}) setImmediate () = > {console.log (' setImmediate') process.nextTick (() = > {console.log ('nextTick3')})}) process.nextTick (() = > {console.log (' nextTick1')}) Process.nextTick (() = > {console.log ('nextTick2')})}) / / nextTick1 nextTick2 setImmediate nextTick3 setTimeoutnextTick application scenario
Perform cpu computationally intensive tasks across multiple events
Var http = require ('http'); function compute () {process.nextTick (compute)} http.createServer (function (req,res) {/ / Service request, still have time to do some computing tasks; res.writeHead (200,{' Content-type': 'text/plain'}) res.end (' hello world');}) compute ()
In this mode, we do not need to call compute () recursively, we just need to use the definition of process.nextTict () in the event loop; compute () can be executed at the next event point; in this process, if a new http request comes in, the event loop mechanism will first process the new request and then call copute (). On the other hand, if you call compute () in a recursion, the system will always be blocked in compute () and will not be able to process new http requests.
The principle of keeping callback functions executed asynchronously
When defining a callback function for a function, make sure that the callback is executed asynchronously (define a callback, but need to use this variable in callback)
The following example violates this principle:
Function asyncFake (data,callback) {/ / synchronously execute if (data = 'foo') callback (true) else callback (false)} asyncFake (' bar',function (result) {/ / this callback is actually called synchronously!})
Why is this not good? Take a look at the following code in the nodejs document
Var client = net.connect (8124, function () {console.log ('client connect'); client.write (' world'); / / will report an error})
In the above code, if for some reason net.connect () becomes synchronous, the callback function will be executed immediately, so the variables written to the client side by the callback function will not be initialized; in this case, we can use process.nextTick () to change the above asyncFake to be executed asynchronously
Function asyncReal (data, callback) {process.nextTick (function () {callback (data = 'foo')})}
Used in the event trigger process
EventEmitter has two core methods, on and Emit. Publish / subscribe model built into node
Var EventEmitter = require ('events'). EventEmmiter;function StreamLibrary (resourceName) {this.emit (' start')} StreamLibrary.prototype.__proto__ = EventEmitter.prototype; / / inherit from EventEmittervar stream = new StreamLibrary ('fooResouce'); stream.on (' start', function () {console.log ('Reading has started')})
When the above code is in new StreamLibrary, emit has already been triggered, and there is no subscription at this time. Console.log will not execute the solution as follows: wrap it in an asynchronous method
Function StreamLibrary (resource) {var self = this; / / guarantee subscription before publication process.nextTick (function () {self.emit ('start');}) / / read from the file,and for every chunck read.do;this.emit (' data', chunkRead)}
Publish and subscribe model
Const EventEmitter = require ('events'). EventEmitter;class App extends EventEmmiter {} let app = new App (); app.on (' start', () = > {/ / subscribe console.log ('start');}) app.emit (' start') / / emit trigger, emit is a synchronous method console.log / / if you need emit to be asynchronous, there are three asynchronous ways to wrap / / start 1111.Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
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.