Until this day I thought I knew how the event loop in javascript works, but I've faced a really strange issue. Maybe it's not strange for you, then I'd appreciate it if you can explain it to me, so here the example of code:
Promise.resolve()
.then(() => {
Promise.resolve().then(() => {
Promise.resolve().then(() => {
Promise.resolve().then(() => {
console.log('first mega inner then')
})
console.log('first very inner then')
})
console.log('first inner then')
})
console.log('first then')
})
.then(() => {
Promise.resolve().then(() => {
Promise.resolve().then(() => {
console.log('second very inner then')
})
console.log('second inner then')
})
console.log('second then')
})
Why is the order of console.logs is:
- first then
- first inner then
- second then
- first very inner then
- second inner then
- first mega inner then
- second very inner then
I personally expected it to be:
- first then
- first inner then
- first very inner then
- first mega inner then
- second then
- second inner then
- second very inner then
But it's not the end... The most interesting thing for me is when I add queueMicrotask after the second "then"
some code here...
.then(() => {
Promise.resolve().then(() => {
Promise.resolve().then(() => {
console.log('second very inner then')
})
console.log('second inner then')
})
console.log('second then')
})
queueMicrotask(() => console.log('microtask'))
IT EXECUTES AFTER THE FIRST "THEN", so the order now is:
- first then
- microtask
- first inner then
- second then
- first very inner then
- second inner then
- first mega inner then
- second very inner then
What is going on? I understand nothing. I think this is the last thing I don't understand in JS and I will be very grateful to you if you can explain why it works like that, I won't be able to sleep till I know this