Understanding the node.js and process.nextTick event queue

I'm having trouble understanding how process.nextTick does its thing. I thought I understood, but I can’t reproduce 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 executing the loop, I will send several requests, assuming that the handler will queue several times behind foo with a callback in the queue only after foo completes.

If I'm right how this works, I assume that the result will look like this:

 received received received received bar bar bar bar 

But it is not, it is simply consistent:

 received bar received bar received bar received bar 

I see that foo returns before making a callback , which is expected, but it seems that the callback is NEXT in the line, and not at the end of the queue, for all incoming requests. what does it work? Perhaps I just don’t understand how the event queue in node works. And please do not point me here . Thanks.

+7
source share
2 answers

process.nextTick places the callback of the next tick to be executed, and not at the end of the tick queue.

Node.js doc ( http://nodejs.org/api/process.html#process_process_nexttick_callback ): "It usually fires before other I / O event events are fired, but there are some exceptions."

setTimeout (callback, 0) will probably work more than what you describe.

+2
source

You should definitely read the fgascon link, and maybe

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

Use process.nextTick if you want to call some code before any IO, but after the called context has returned (usually because you want to register listeners on the event emitter and must return the created emitter before you can register something- or).

+1
source

All Articles