What events specify when a tick ends in node.js?
I've read that a tick is a unit of execution where the nodejs event loop decides to run everything in its queue, but other than explicitly saying process.nextTick()
what events cause the node.js event loop to start processing a new tick? Is it waiting on I/O? What about cpu bound computations? Or is it whenever we enter a new function?
process.nextTick()
does not cause Node.JS to start a new tick. It causes the provided code to wait for the next tick.
This is a great resource for understanding it: http://howtonode.org/understanding-process-next-tick
As far as getting events for a tick, I don't believe the runtime provides that. You could "fake" it like:
var tickEmitter = new events.EventEmitter();
function emit() {
tickEmitter.emit('tick');
process.nextTick( emit );
}
tickEmitter.on('tick', function() {
console.log('Ticked');
});
emit();
Edit: To answer some of your other questions, another post does an exceptional job of demonstrating: What exactly is a Node.js event loop tick?
nextTick
registers a callback to be called when when the currently executing Javascript returns control back to the event loop (eg finishes executing). For a CPU-bound operation, this will be when the function is finished. For an async operation, this will be when the async operation is started and any other immediate code is done (but not when the async operation itself has completed as that will go in the event queue when it finishes to be serviced from the event queue).
From the node.js doc for process.nextTick()
:
Once the current event loop turn runs to completion, call the callback function.
This is not a simple alias to setTimeout(fn, 0), it's much more efficient. It runs before any additional I/O events (including timers) fire in subsequent ticks of the event loop.
Some examples:
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");
Output:
A
E
B
C
D
链接地址: http://www.djcxy.com/p/29928.html
上一篇: 使用数据分组输入