7

我很难理解它到底是怎么process.nextTick做的。我以为我理解了,但我似乎无法复制我认为这应该如何工作:

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循环时,我将发送几个请求,假设handler将在后面排队几次foocallback只有在foo完成时才入队。

如果我对它的工作原理是正确的,我假设结果将如下所示:

received
received
received
received
bar
bar
bar
bar

但它没有,它只是顺序的:

received
bar
received
bar
received
bar
received
bar

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.

4

2 回答 2

2

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 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) will probably work more like you describe.

于 2013-04-25T18:44:51.297 回答
1

You should certainly read the link fgascon provided, and perhaps

https://github.com/joyent/node/issues/3335 for more background.

Use process.nextTick for when you want to call some code before any IO, but after the calling context has returned (usually because you want to register listeners on an event emitter and need to return the created emitter before you can register anything).

于 2013-05-07T00:20:58.683 回答