I am trying to get a better understanding of the Nodejs event loop and have got to the different types of queues that are used under the covers. My question is related to the micro queue used for promises.
From everything I have read, my current understanding is that the micro queue used for promises works on a FIFO basis (first in first out). However I have a small piece of example code that doesn't make sense to me following that principle.
const promise1 = Promise.resolve();
const promise2 = Promise.resolve();
promise2.then(function p2() {
console.log('in promise2.then()')
})
promise1.then(function p1() {
console.log('in promise1.then()')
})
console.log('end test')
So from my current (quite possibly flawed understanding) of the order of events that will take place here is
promise1
resolves instantly causing its handler (p1
) to be added to the micro queuepromise2
resolves instantly causing its handler (p2
) to be added to the micro queueconsole.log('end test')
gets added to the stack, instantly popped resulting in the log being printed- Now that the stack is empty the
p1
handler is picked off the queue (FIFO) and added to the stack resulting inin promise1.then()
being printed - The
p2
handler is picked off the queue and added to the stack resulting inin promise2.then()
being printed
This would result in an output of
end test
in promise1.then()
in promise2.then()
However what I am actually getting is
end test
in promise2.then()
in promise1.then()
I've even tried to run it through a visualiser like this https://www.jsv9000.app/?code=Y29uc3QgcHJvbWlzZTEgPSBQcm9taXNlLnJlc29sdmUoKTsKY29uc3QgcHJvbWlzZTIgPSBQcm9taXNlLnJlc29sdmUoKTsKCnByb21pc2UyLnRoZW4oZnVuY3Rpb24gcDIoKSB7CiAgY29uc29sZS5sb2coJ2luIHByb21pc2UyLnRoZW4oKScpCn0pCnByb21pc2UxLnRoZW4oZnVuY3Rpb24gcDEoKSB7CiAgY29uc29sZS5sb2coJ2luIHByb21pc2UxLnRoZW4oKScpCn0pCmNvbnNvbGUubG9nKCdlbmQgdGVzdCcp
My understanding seems to hold up while the handlers are being added to the micro queue but then everything falls apart once it starts picking things off.
My question is how is the p2
handler being picked off the micro queue and run before the p1
handler if the microqueue is a FIFO system?