nodejs(五)同步异步--BLOCKING THE EVENT LOOP

1.BLOCKING THE EVENT LOOP
  Node and JavaScript runtimes in general are single-threaded event loops. On each loop, the runtime
processes the next event in queue by calling the associated callback function. When that event
is done, the event loop fetches and processes the next event; this pattern continues until the queue is
empty. If one of these callbacks takes a long time, the event loop won’t process pending events in the
meantime. This can lead to a slow application or service.
  Using memory- or processor-intensive functions when handling events can lead to the event loop
becoming slow and the events becoming queued up and unserved or even blocked.
Here is an example of blocking the event loop:

process.nextTick(function nextTick1() {
  var a = 0;
  while(true) {
    a ++;
  }
});
process.nextTick(function nextTick2() {
  console.log("next tick");
});
setTimeout(function timeout() {
  console.log("timeout");
}, 1000);

In this case, the nextTick2 and timeout functions will never have the chance to run no matter how
long you wait because the event loop is blocked by an infinite cycle inside the first nextTick function.
Even the scheduled timeout function that was supposed to run after one second does not run.
When using setTimeout, the callback function goes into a scheduling queue, which, in this
case, doesn’t even get to be dispatched. This is an extreme case, but you can see how running a
processor-intensive task may block or slow down your event loop.

2.ESCAPING THE EVENT LOOP
  By using process.nextTick, you can now defer the execution of a non-crucial task to the next tick,
freeing the event loop to execute other pending events.
As an example, if you need to remove a temporary fi le you created, but perhaps you don’t need to do
it before replying to the client, you can defer it like this:

1 stream.on("data", function(data) {
2   stream.end("my response");
3   process.nextTick(function() {
4     fs.unlink("/path/to/file");
5   });
6 });