DEV Community

loading...

Discussion on: Understanding the Node.js event loop phases and how it executes the JavaScript code.

Collapse
artoodeeto profile image
aRtoo

Thank you for the response sir. Last question it only happens in their execution context right? say I have this code:

console.log('bar')

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

f()
setImmediate( ()=> console.log('immediate') )

output:
bar
immediate
foo

even though I called f() first before setImmediate

Thread Thread
lunaticmonk profile image
Sumedh Nimkarde Author

Hey, pardon for the late reply. Yes, it happens in the execution context. Thanks for reminding, I think I forgot to mention this term in the article! By the way, I think you may have mistaken for the output, after executing, the output seems to be:

bar
foo
immediate

Here is how it happens:

  1. console.log gets logged
  2. f is called. f()
  3. now, everything happens according to the f() context. i.e process.nextTick will execute with priority. If there are any other setTimeout, setImmediate callbacks, they will be pushed to the respective queues and executed.
  4. lastly, when the function returns, we come back to the last setImmediate, and execute the callback.
Thread Thread
artoodeeto profile image
aRtoo

I never tried my code. I thought process.nextTick will be push to event loop and setImmediate will run next since its in the higher or outer execution context.

anyway thanks for explaining. :)