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
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With