When I was writting some code I bump into incorrect as I think behaviour of nextTick queue and microtask queue.
Ok, example of the code will be the following:
process.nextTick(() => console.log(1));
Promise.resolve().then(() => console.log(2));
Promise.resolve().then(() => console.log(3));
setImmediate(() => {
Promise.resolve().then(() => console.log(4));
process.nextTick(() => console.log(5));
});
it will output:
2
3
1
5
4
However, If I'll wrap that code into setTimeout
setTimeout(() => {
process.nextTick(() => console.log(1));
Promise.resolve().then(() => console.log(2));
Promise.resolve().then(() => console.log(3));
setImmediate(() => {
Promise.resolve().then(() => console.log(4));
process.nextTick(() => console.log(5));
});
})
you will see another order of outputs:
1
2
3
5
4
So why do I see that microtask will be first rather than nextTick without wrapping by setTimeout?
Node.js version
v18.9.0