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

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

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

> What are the proper use cases for process.nextTick in Node.js?

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

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...