which executes first, nextTick or promises? [duplicate]
Asked Answered
B

0

0

i'm trying to understand the output of a test that i've been running because it seems to go against everything that i'm reading and hearing about how the node.js event loop works. supposedly all callbacks in the nextTick queue are executed before all callbacks in the promise queue but when i run this snippet

Promise.resolve().then(() => console.log('promise'))
process.nextTick(() => console.log('nextTick'))

i get this

promise
nextTick

i get the same output if i change the code to this

new Promise((resolve, reject) => resolve('promise')).then((resolve) => console.log(resolve))
process.nextTick(() => console.log('nextTick'))

why is that? i'm running v21.7.2 of node btw

this is one of the videos that i've watched that states that nextTick always runs before promises. (the video plays right at the point where an example is given) Node.js Tutorials - 43 - Microtask Queues

Boyle answered 17/4 at 10:11 Comment(8)
They both do different things with asynchronous code; Promises execute after I/O events but before setTimeout() and setImmediate() callbacks. process.nextTick() callbacks execute before I/O events or timers.Nanete
Does a promise that immediately resolves get added to the Promise queue? I always though that if it's not actually waiting, it will just pick up immediately? That's because the promise would execute your handler immediately, and immediately be marked as completed, which would then immediately execute the callback?Prepotency
@Prepotency then is always putting the callback in the microtask queue, no matter when the promise is being (or was) resolved.Giorgione
@Giorgione Learning every day.Prepotency
Yup, not much different than the behavior of setTimeout with a 0ms delay.Cisneros
"I get this: promise nextTick": that's the order I would expect if that code runs as a result of a promise resolution. If it executes synchronously in the main script, I would expect the opposite order (and that is what I get).Evangelical
To clarify/nit-pick over Bergi's comment, in case the promise isn't resolved yet it's not really the then() call that pushes the callback into the microtask queue, it's whatever task resolved the promise. This may give funky ordering stuff when doing so from node's nextTick + promise-queue, microtask queues, since they'll loop to each other before returning to the actual event-loop. (But their point that a .then() callback always ends up in a microtask is very valid).Uhl
To be sure, you were running your project as ESM, right?Uhl

© 2022 - 2024 — McMap. All rights reserved.