Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS eventloop execution order(process.nextTick and promise)

Run code below will get:c,a,d,b

// case 1
const test = async () => {
  new Promise((resolve) => {
    resolve('a');
  }).then(r => console.log(r));

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

  console.log(await 'd');

  return 'b';
};
(async () => {
  const r = await test();
  console.log(r);
})();

but, if I put process.nextTick below await 'd'

// case 2
const test = async () => {
  new Promise((resolve) => {
    resolve('a');
  }).then(r => console.log(r));

  console.log(await 'd');

  process.nextTick(() => {
    console.log('c');
  });
  new Promise((resolve) => {
    resolve('e');
  }).then(r => console.log(r));

  return 'b';
};
(async () => {
  const r = await test();
  console.log(r);
})();

I get: a,d,e,b,c

why process.nextTick's execution order changes like this?

According to my limitted knowledege, nextTick runs before Promise.resolve() as shown in case1, so I expected to get a,d,c,e,b rather than a,d,e,b,c in case2

like image 278
cody Avatar asked Mar 02 '26 00:03

cody


1 Answers

Disclaimer

Node.js makes absolutely no guarantees on the order of process.nextTick and promise callbacks.

We may break this in a patch version since we do not consider it a part of the public API.

You may not rely on the internal order of promises and nextTicks in order to do things.


This particular case

This particular case was a "bug" in how we handled promises/callbacks sometimes. It was recently fixed (in a semver-patch) - by getting a nightly version of Node you'll see the expected execution order.

like image 66
Benjamin Gruenbaum Avatar answered Mar 04 '26 14:03

Benjamin Gruenbaum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!