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

Process.nextTick usage example in Node.js

高洛峰
Release: 2016-12-26 09:16:30
Original
1504 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 then give the 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

Simply put, 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 placed at the top level 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.

For more articles related to process.nextTick usage examples in Node.js, please pay attention to the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!