process.nextTick将回调放入队列。此队列中的每个回调将在事件循环的下一个滴答的开始处执行。基本上,它用作清除调用堆栈的一种方法。当文档说像时
setTimeout,意味着说像
setTimeout(function(){ ... }, 1)在浏览器中使用。它具有相同的用例。一个示例用例是,为需要绑定事件的某些对象创建一个构造函数。但是,您无法立即开始发出事件,因为实例化它的代码还没有时间绑定到事件。您的构造函数调用在调用堆栈中位于它们之上,并且如果您继续执行同步操作,它将保持这种状态。在这种情况下,您可以
process.nextTick在继续进行任何操作之前使用“
a” 。它保证使用您的构造函数的人将有足够的时间绑定事件。
例:
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);}


