When run the below code snippet, it outputs 2,1
. Since Promise is a micro-task and everything inside a promise should run before a macro-task (setTimeout), I expect that the output will be 1,2
. So even if there is a macro-task inside a micro-task, I thought the output will be 1,2
.
But it outputs 2,1
.
What’s the catch here? Why does it outputs 2,1
instead 1,2
?
JavaScript
x
10
10
1
Promise.resolve().then(() => {
2
setTimeout(() =>{
3
console.log("1")
4
}, 0)
5
})
6
7
setTimeout(() => {
8
console.log("2")
9
}, 0)
10
Advertisement
Answer
The promise is a micro task and will get executed before timeout1
, but timeout1
is already scheduled as a macro task.
When the promise resolves, timeout2
will get scheduled, but the macrotask Q already has timeout1
and as such this is already scheduled and will get executed first.