The following program will hang in NodeJS, does anybody know why?
ended = false; events = require('events'); eventEmitter = new events.EventEmitter(); eventEmitter.on('end', function() { ended = true; }); setTimeout(function() { eventEmitter.emit('end'); }, 100); while (!ended) { process.nextTick(); } console.log('ended');
nextTick
isn't some kind of yield operation, it's for scheduling a callback to be called the next time the engine is free to do so. It's "hanging" because the while
loop's exit condition is never satisfied (and can never be, with that code).
Short answer: because Node.JS is single-threaded.
Long answer: JavaScript is organized into a queue which holds events. These events when fired cannot be stopped until they finish the job. Also no other code can run parallelly, because Node.JS is single threaded. What this means is that this code:
while (!ended) {
process.nextTick();
}
is an infinie loop. The ended
variable will never change, because end
handler cannot fire until the main event (i.e. the code you've shown us) finishes its job. And it never does.
process.nextTick();
does not call the next cycle of the main loop, the next cycle comes automatically, .nextTick()
method is used to call a callback function on the next cycle, info: http://nodejs.org/api/process.html#process_process_nexttick_callback.
while(!ended)
is an infinite loop and that's why the application hangs, the ended
variable will not change until the current cycle does not end, which is flooded by your while loop.