Javascript 在node.js中,什么事件指定记号何时结束?

Javascript 在node.js中,什么事件指定记号何时结束?,javascript,node.js,single-threaded,Javascript,Node.js,Single Threaded,我已经读过,tick是一个执行单元,其中nodejs事件循环决定运行其队列中的所有内容,但除了明确表示process.nextTick()是什么事件导致node.js事件循环开始处理新的tick之外?它正在等待I/O吗?cpu限制的计算呢?或者是每当我们输入一个新函数时 nextTick注册一个回调,当当前执行的Javascript将控制权返回到事件循环(例如,完成执行)时调用该回调。对于CPU限制的操作,这将在函数完成时进行。对于异步操作,这将发生在异步操作启动和任何其他立即代码完成时(但不会

我已经读过,tick是一个执行单元,其中nodejs事件循环决定运行其队列中的所有内容,但除了明确表示
process.nextTick()
是什么事件导致node.js事件循环开始处理新的tick之外?它正在等待I/O吗?cpu限制的计算呢?或者是每当我们输入一个新函数时

nextTick
注册一个回调,当当前执行的Javascript将控制权返回到事件循环(例如,完成执行)时调用该回调。对于CPU限制的操作,这将在函数完成时进行。对于异步操作,这将发生在异步操作启动和任何其他立即代码完成时(但不会发生在异步操作本身已完成时,因为当异步操作完成从事件队列提供服务时,它将进入事件队列)

从:

当前事件循环运行完成后,调用回调函数

这不是setTimeout(fn,0)的简单别名,它更重要 有效率的它在任何附加I/O事件(包括计时器)之前运行 在事件循环的后续标记中激发

一些例子:

console.log("A");
process.nextTick(function() { 
    // this will be called when this thread of execution is done
    // before timers or I/O events that are also in the event queue
    console.log("B");
});
setTimeout(function() {
    // this will be called after the current thread of execution
    // after any `.nextTick()` handlers in the queue
    // and after the minimum time set for setTimeout()
    console.log("C");
}, 0);
fs.stat("myfile.txt", function(err, data) {
    // this will be called after the current thread of execution
    // after any `.nextTick()` handlers in the queue
    // and when the file I/O operation is done
    console.log("D");
});
console.log("E");
输出:

A
E
B
C
D
process.nextTick()
不会导致Node.JS开始新的勾号。它会导致提供的代码等待下一个滴答声

这是了解它的一个很好的资源:

就获取事件而言,我不相信运行时提供了这一点。你可以像这样“伪装”它:

编辑:为了回答您的其他一些问题,另一篇文章做了一项出色的工作,展示了:

var tickEmitter = new events.EventEmitter();
function emit() {
    tickEmitter.emit('tick');
    process.nextTick( emit );
}
tickEmitter.on('tick', function() {
    console.log('Ticked');
});
emit();