Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

javascript - understanding the node.js event queue and 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);

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...