watchdog watchdog - 2 months ago 8
Node.js Question

Newcomer to Node, how to understand process.nextTick()

code1:

function foo() {
console.log('foo');
}
process.nextTick(foo);
console.log('bar');


code2:

function foo() {
console.log('foo');
}
foo();
console.log('bar');


The first piece of code output:

bar
foo


and the second is opposite:

foo
bar


why?

My question is :


  1. How to understand "what process.nextTick() actually does is defer the execution of an action till the next pass around the event loop"

  2. Actually, I don't know the concept of 'event', console.log('bar') is an event? foo() is an event? process.nextTick(foo) is an event?



Thank you guys.

Answer

process.nextTick(foo) schedules foo() to be called after the current thread of JS execution finishes. It does this by essentially inserting a call to foo() at the front of the event queue. When the current thread of JS execution finishes, the node.js engine will pull the next event off the event queue and run it. This will cause you to get your output:

bar
foo

Because console.log('bar') is part of the current thread of execution so that will finish before the next event in the event loop is serviced.

So, in words, here's what the code1 example is doing:

  1. Define foo function (this is actually done by the parser before anything executes)
  2. Run process.nextTick(foo) which schedules foo() to be run after the rest of this thread of Javascript finishes by inserting an event in the event queue. All callbacks or functions to be run in the future are scheduled this way in node.js (via the event queue). node.js is an event driven environment.
  3. Run console.log('bar').
  4. Current thread of JS finishes execution.
  5. System pulls next event from the event queue and runs it.
  6. This next event is the call to foo() from the process.nextTick() call.
  7. foo() runs.

In your code2 example, this is just sequential execution. Nothing is inserted in the event queue at all. foo() is executed and then when that function returns, the console.log('bar') is executed.


So process.nextTick() is used to explicitly schedule something to run later after the current thread of JS execution has finished.

It's similar to setTimeout(), but process.nextTick() runs as soon as possible after the current thread of execution whereas setTimeout() can be set with a specific time delay.


It appears your code example is taken from this article: Understanding process.nextTick(). There is a lot more explanation in that article.

Another reference: What are the proper use cases for process.nextTick in Node.js?

Comments