了解node.js事件队列和process.nextTick [英] understanding the node.js event queue and process.nextTick
问题描述
我无法理解 process.nextTick
的功能。我想我明白,但我似乎无法复制我觉得这应该工作:
I'm having trouble understanding exactly how process.nextTick
does its thing. I thought I understood, but I can't seem to replicate how I feel this should work:
var handler = function(req, res) {
res.writeHead(200, {'Content-type' : 'text/html'});
foo(function() {
console.log("bar");
});
console.log("received");
res.end("Hello, world!");
}
function foo(callback) {
var i = 0;
while(i<1000000000) i++;
process.nextTick(callback);
}
require('http').createServer(handler).listen(3000);
当 foo
循环时发送多个请求,假设处理程序
将排队几次后 foo
与 callback
只有在 foo
完成后才会入列。
While foo
is looping, I'll send over several requests, assuming that handler
will be queued several times behind foo
with callback
being enqueued only when foo
is finished.
工作,我认为结果将如下所示:
If I'm correct about how this works, I assume the outcome will look like this:
received
received
received
received
bar
bar
bar
bar
但它不是,它只是顺序:
But it doesn't, it's just sequential:
received
bar
received
bar
received
bar
received
bar
看到 foo
在执行回调
之前正在返回,这是预期的,但似乎 callback
是NEXT在线,而不是在队列的末尾,所有的请求进来后。这是它的工作原理吗?也许我只是不明白节点中的事件队列是如何工作的。请不要指向我此处。感谢。
I see that foo
is returning before executing callback
which is expected, but it seems that callback
is NEXT in line, rather than at the end of the queue, behind all of the requests coming in. Is that the way it works? Maybe I'm just not understanding how exactly the event queue in node works. And please don't point me here. Thanks.
推荐答案
process.nextTick将回调放在要执行的下一个tick上,而不是在tick队列。
process.nextTick put the callback on the next tick that is going to be executed, not at the end of the tick queue.
Node.js文档( http://nodejs.org/api/process.html#process_process_nexttick_callback )say:
通常在任何其他I / O事件触发之前运行,但有一些例外。
Node.js doc (http://nodejs.org/api/process.html#process_process_nexttick_callback) say: "It typically runs before any other I/O events fire, but there are some exceptions."
setTimeout(callback,0)可能更像你描述的。
setTimeout(callback, 0) will probably work more like you describe.
这篇关于了解node.js事件队列和process.nextTick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!