What will be the order of following code:
console.log(1) const promise = new Promise((resolve) => { console.log(2) resolve() console.log(3) }) console.log(4) promise.then(() => { console.log(5) }).then(() => { console.log(6) }) console.log(7) setTimeout(() => { console.log(8) }, 10) setTimeout(() => { console.log(9) }, 0)
Let me explain the execution order of this code:
The output will be: 1, 2, 3, 4, 7, 5, 6, 9, 8
Here's why:
First, synchronous code executes:
console.log(1)
executes firstconsole.log(2)
and console.log(3)
run nextconsole.log(4)
runs nextconsole.log(7)
runs after thatThen microtasks (Promise callbacks) execute:
.then()
executes, printing console.log(5)
.then()
executes, printing console.log(6)
Finally, macrotasks (setTimeout callbacks) execute:
setTimeout
with 0ms delay prints console.log(9)
setTimeout
with 10ms delay prints console.log(8)
Key points to understand:
.then()
callbacks are microtasks and execute after all synchronous code but before macrotaskssetTimeout
callbacks are macrotasks and execute after microtaskssetTimeout
, the one with shorter delay executes first (0ms vs 10ms)