PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

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

高洛峰
高洛峰 原创
2016-12-26 09:16:30 1286浏览

我已经不记得是在哪里第一次看到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);
}

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

更多Node.js中的process.nextTick使用实例相关文章请关注PHP中文网!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。