时间:2021-05-26
我已经不记得是在哪里第一次看到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);}简单来说就是因为异步模型的关系,导致某些代码的执行可能先于它们所需要的条件完成之前,所以将这些需要先置条件的代码放入到一个回调函数中,然后放入到下一个事件循环的顶层。那么这些代码就不会被立刻执行了,而是在下一轮事件启动之前等待,启动后在进行执行。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
Node.js和js一样也有计时器,超时计时器、间隔计时器、及时计时器,它们以及process.nextTick(callback)函数来实现事件调度。今天先学
本文介绍了详解promise.then,process.nextTick,setTimeout以及setImmediate的执行顺序,分享给大家,具体如下:先举
Linux使用Node.js建立访问静态网页的服务实例详解一、安装node.js运行所需要的环境,:二、创建node目录(/node/www),并在目录下创建n
本文实例讲述了node.js中fs文件系统模块的使用方法。分享给大家供大家参考,具体如下:node.js中为我们提供了fs文件系统模块,实现对文件或目录的创建,
什么是Node.js的模块(Module)?在Node.js中,模块是一个库或框架,也是一个Node.js项目。Node.js项目遵循模块化的架构,当我们创建了