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:
I personally expected it to be:
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:
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 😂
There may be a misunderstanding of how promise is used here. In promise chaining, the .then method is activated as soon as the promise resolves. If you want to delay the action of the second part of the chain, you need to specify when to resolve in a new promise. This example shows how that would work.
When you call Promise.resolve().then it calls the resolve method of the Promise class and makes the then method available immediately. Although you are not delaying the resolve when calling the resolve method immediately, it still takes some time to preform the resolve, so the following line of code will not be blocked.
Hopefull this provides some insight into the magic of Promise in js
(new Promise(resolve => {
Promise.resolve().then(() => {
Promise.resolve().then(() => {
Promise.resolve().then(() => {
console.log('first mega inner then')
resolve();
})
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');
});