mkorman
mkorman

Reputation: 352

What's the Node's execution order in this example

The common example of presenting the functionality of setImmediate function in Node JS is the following code

console.log('1');
setImmediate(() => console.log('2'));
console.log('3');

which evaluates to

1
3
2

As far as I know setImmediate callbacks are executed during check phase of event loop

node js event loop

However I don't understand where fetching new, sequential instruction fits there? Are we guaranteed that Node will fetch and execute console.log('3') BEFORE executing the check phase and therefore print 3 before 2? If so - how many such instruction would Node execute before reaching check phase?

Upvotes: 2

Views: 557

Answers (1)

CherryDT
CherryDT

Reputation: 29011

However I don't understand where fetching new, sequential instruction fits there?

No need to fetch anything new because all the instructions have to be loaded already at that point, since we are already in the middle of executing them!

  1. It is determined that your code should run
  2. Your code (all 3 lines) runs
  3. Event loop is entered and checks what else is there to do
  4. It is determined that the callback should run
  5. The callback (all "1 lines") runs
  6. ...

Are we guaranteed that Node will fetch and execute console.log('3') BEFORE executing the check phase and therefore print 3 before 2?

Yes.

If so - how many such instruction would Node execute before reaching check phase?

Infinitely many.

JavaScript is single-threaded* and there nothing can preempt your code (other than a Ctrl+C).

So, the following code will keep outputting 3 in all eternity and never get to 2**:

console.log('1');
setImmediate(() => console.log('2'));
while (true) {
  console.log('3');
}
1
3
3
3
3
... (forever)

Similarly, the following code will for all eternity print 2A and never get to 2B:

console.log('1');
setImmediate(() => {
  while (true) {
    console.log('2A');
  }
});
setImmediate(() => console.log('2B'));
console.log('3');
1
3
2A
2A
2A
2A
... (forever)

(The same applies if you were to move the setImmediate(() => console.log('2B')); inside the first callback instead of putting it below it.)

*: Yes there are worker threads in node.js and service workers in the browser, but they live in their own environments.

**: ...consuming 100% of one CPU core in the process and not reacting to any events or signals, so consider this an example of academic interest only, not something you would ever write in real code.

Upvotes: 4

Related Questions