当节点在node.js中结束时,会指定哪些事件?

oib*_*ibe 7 javascript single-threaded node.js

我已经读过tick是一个执行单元,其中nodejs事件循环决定运行其队列中的所有内容,但除了明确说明process.nextTick()哪些事件导致node.js事件循环开始处理新的tick?是等待I/O吗?那么cpu绑定计算呢?或者只要我们输入新功能?

jfr*_*d00 1

nextTick注册一个回调,当当前执行的 Javascript 将控制返回到事件循环(例如完成执行)时调用。对于 CPU 密集型操作,这将是函数完成时的情况。对于异步操作,这将是当异步操作启动并且任何其他立即代码完成时(但不是当异步操作本身完成时,因为当它完成从事件队列的服务时,它将进入事件队列) 。

来自node.js 文档process.nextTick()

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

这不是 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");
Run Code Online (Sandbox Code Playgroud)

输出:

A
E
B
C
D
Run Code Online (Sandbox Code Playgroud)