Node.js中的process.nextTick使用实例


我已经不记得是在哪里第一次看到process.nextTick这个玩意的调用了,哦,应该是在nodejs官方的process文档里看到的。当时就不理解这东西是干嘛的了,都已经有setTimeout了,还需要这个函数干嘛。而且从根本上来说,这个函数又是干嘛的?和setTimeout有什么区别?

stackoverflow上有一个非常好的帖子基本上解释了我的问题,这里我附上链接,然后给出它里面的范例:

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);
}

 

简单来说就是因为异步模型的关系,导致某些代码的执行可能先于它们所需要的条件完成之前,所以将这些需要先置条件的代码放入到一个回调函数中,然后放入到下一个事件循环的顶层。那么这些代码就不会被立刻执行了,而是在下一轮事件启动之前等待,启动后在进行执行。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3