salezica
salezica

Reputation: 76949

Are callbacks of process.nextTick invoked in order?

If you call process.nextTick() multiple times, are the callbacks executed in order?

In other words, does the Node event loop give the same priority to all calls to process.nextTick, and execute them in FIFO order?

For example:

process.nextTick(() => console.log('1'))
process.nextTick(() => console.log('2'))

process.nextTick(() =>
  process.nextTick(() => console.log('3'))
)

process.nextTick(() =>
  process.nextTick(() => console.log('4'))
)

Will this always print 1 2 3 4?

Upvotes: 4

Views: 206

Answers (1)

Antonio Val
Antonio Val

Reputation: 3340

What kind of queue is being used is not written in the docs, and I could not find an official source that explains it, so I took a look to the source code and it seems it is a FIFO queue as you pointed.

Check how the callbacks are pushed into the nextTickQueue array after each nextTick(), and how they are executed after in order in _tickCallback(), incrementing the index tickInfo[kIndex] in each iteration of the while loop.

I think in your example the third and fourth callbacks would not be at the same time in the queue with the first and second; but they would be executed in that order anyway.

By the way, even being a FIFO order of execution the expected way, this is an undocumented behaviour, so it is not recommended to rely on it; internal stuff can change anytime.

Upvotes: 2

Related Questions