Home > Web Front-end > JS Tutorial > Process.nextTick usage example in Node.js_node.js

Process.nextTick usage example in Node.js_node.js

WBOY
Release: 2016-05-16 15:52:58
Original
1300 people have browsed it

I can’t remember where I first saw the call to process.nextTick. Oh, I should have seen it in the official nodejs process document. At that time, I didn’t understand what this thing was for. We already had setTimeout, so why did we need this function? And fundamentally speaking, what does this function do? What is the difference between setTimeout and setTimeout?

There is a very good post on stackoverflow that basically explains my problem. Here I attach the link and give an example in it:

stackoverflow.com >> What are the proper use cases for process.nextTick in Node.js?

var MyConstructor = function() {
 ...
 process.nextTick(function() {
  self._continue();
 });
};
 
MyConstructor.prototype.__proto__ = EventEmitter.prototype;
 
MyConstructor.prototype._continue = function() {
 // without the process.nextTick
 // these events would be emitted immediately
 // with no listeners. they would be lost.
 this.emit('data', 'hello');
 this.emit('data', 'world');
 this.emit('end');
};
 
function(req, res, next) {
 var c = new MyConstructor(...);
 c.on('data', function(data) {
  console.log(data);
 });
 c.on('end', next);
}
Copy after login

To put it simply, because of the asynchronous model, some codes may be executed before the conditions they require are completed, so put these codes that require preconditions into a callback function, and then put Go to the top of the next event loop. Then these codes will not be executed immediately, but will wait before the next round of events is started, and will be executed after starting.

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