手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >Node.js中的process.nextTick使用实例
Node.js中的process.nextTick使用实例
摘要:我已经不记得是在哪里第一次看到process.nextTick这个玩意的调用了,哦,应该是在nodejs官方的process文档里看到的。当...

我已经不记得是在哪里第一次看到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使用实例】相关文章:

JQuery中层次选择器用法实例详解

js中setTimeout()与clearTimeout()用法实例浅析

JavaScript中的anchor()方法使用详解

JavaScript中for循环的使用详解

JavaScript中的Math.SQRT1_2属性使用简介

jquery中map函数遍历数组用法实例

javaScript中slice函数用法实例分析

JavaScript中的pow()方法使用

Node.js中JavaScript操作MySQL的常用方法整理

JavaScript中exec函数用法实例分析

精品推荐
分类导航