process.nextTick vs queueMicrotask in commonJs and ESM. What is the execution order?

Viewed 126

Let's imagine we have a file containing next JS code:

process.nextTick(()=>{
    console.log('nextTick')
})

queueMicrotask(()=>{
    console.log('queueMicrotask')
})

console.log('console.log')

and we've set module system to "type": "commonjs" in our package.json

What output in console do we expect? Node.js official documentation says:

The process.nextTick() queue is always processed before the microtask queue within each turn of the Node.js event loop

So, in console we expect

console.log
nextTick
queueMicrotask

And that works. Until I change module system to "type": "module". After that change I constantly have queueMicrotask executed before process.nextTick . Console output is:

console.log
queueMicrotask
nextTick

Does anybody can explain that behaviour? I can assume that that behaviour somehow related to module evaluation and execution process and that nextTick queueMicrotask somehow get into different event loop ticks as module implies async execution(in browser) but that guess is very shaky and from my point of view is illogical. Nevertheless I still don't have a plausible explanation.

0 Answers
Related