我读过滴答是一个执行单元,nodejs事件循环决定运行其队列中的所有内容,但除了明确说明process.nextTick()
哪些事件导致node.js事件循环开始处理新的滴答?是否在等待 I/O?cpu绑定计算呢?还是每当我们输入一个新功能时?
问问题
1513 次
2 回答
3
process.nextTick()
不会导致 Node.JS 开始新的刻度。它使提供的代码等待下一个滴答声。
这是理解它的一个很好的资源:http: //howtonode.org/understanding-process-next-tick
至于获取事件,我不相信运行时提供了这一点。你可以像这样“伪造”它:
var tickEmitter = new events.EventEmitter();
function emit() {
tickEmitter.emit('tick');
process.nextTick( emit );
}
tickEmitter.on('tick', function() {
console.log('Ticked');
});
emit();
编辑:为了回答您的其他一些问题,另一篇文章做了出色的演示:Node.js 事件循环滴答声到底是什么?
于 2015-10-24T20:24:21.610 回答
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");
输出:
A
E
B
C
D
于 2015-10-24T20:24:15.267 回答