I'm working on some event loop knowledge refinement and I'm a bit stumped at the following code block:
new Promise((resolve) => {
console.log('in here, 1')
setTimeout(() => resolve(3),0);
console.log('in here, 2')
}).then((val) => console.log(val));
new Promise((resolve) => {
console.log('in here, 5')
resolve(4)
console.log('in here, 6')
}).then((val) => console.log(val));
//in here, 1
//in here, 2
//in here, 5
//in here, 6
//4
//3
I understand that the Promise
constructor returns a new Promise
instance synchronously; that the code inside of the executor function in a Promise
constructor runs synchronously; that .then()
returns a new Promise
instance synchronously; but that the onFulfilled
and onRejected
handlers in a .then((onFulfilled, onRejected) => {})
are invoked asynchronously.
I have a few questions regarding the resolve
within the setTimeout
in the first promise
. The callback function in the setTimeout
will resolve the promise with the value of 3
. However, since callbacks from promises
are placed in the microtask queue, and in this case, the .then()
will place a (val) => console.log(val)
on the microtask queue, why can it read the value of the resolved promise
it's attached to? The resolve
is in the timers callback queue which hasn't been processed by the event loop yet because we're inside of the microtask queue. Thus, shouldn't the value read by the .then()
callback in the first promise
be undefined
? I may be misunderstanding how resolve
exactly works in the executor in the constructor.
I could use some clarification on this and maybe on how the microtask queue works in Node. Thank you.