Reputation: 35
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 :
Thank you guys.
Upvotes: 3
Views: 390
Reputation: 707436
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:
foo
function (this is actually done by the parser before anything executes)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.console.log('bar')
.foo()
from the process.nextTick()
call.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?
Upvotes: 2