Middle+
console.log(1) setTimeout(() => { console.log(2) }, 10) setTimeout(() => { Promise.resolve().then(() => console.log(3)) }, 0); setTimeout(() => { console.log(4) }, 0); new Promise((_, reject) => { console.log(5) reject(6) console.log(7) }).then(() => console.log(8)) .catch(() => console.log(9)) .then(() => console.log(10)) .catch(() => console.log(11)) .then(() => console.log(12)) .then(console.log) .finally(() => console.log(13)) console.log(14)
sobes.tech AI
Answer from AI
Let's analyze the order of output to the console step by step:
console.log(1)
setTimeout(() => {
console.log(2)
}, 10)
setTimeout(() => {
Promise.resolve().then(() => console.log(3))
}, 0);
setTimeout(() => {
console.log(4)
}, 0);
new Promise((_, reject) => {
console.log(5)
reject(6)
console.log(7)
}).then(() => console.log(8))
.catch(() => console.log(9))
.then(() => console.log(10))
.catch(() => console.log(11))
.then(() => console.log(12))
.then(console.log)
.finally(() => console.log(13))
console.log(14)
-
Synchronous code executes immediately:
console.log(1)→ 1- In the promise constructor:
console.log(5)→ 5 console.log(7)→ 7console.log(14)→ 14
-
The promise is rejected (
reject(6)), so the.catch()chain is triggered. -
Microtasks (Promise handlers) execute after the current stack:
.catch(() => console.log(9))→ 9.then(() => console.log(10))→ 10.catch()is skipped as there is no error.then(() => console.log(12))→ 12.then(console.log)— receivesundefined(result of previous then), outputsundefined.finally(() => console.log(13))→ 13
-
Macrotasks (
setTimeout) execute after microtasks:setTimeout(..., 0)withPromise.resolve().then(() => console.log(3))— the setTimeout triggers first, inside which a microtask logs 3setTimeout(..., 0)withconsole.log(4)— logs 4setTimeout(..., 10)withconsole.log(2)— logs 2
Final output order:
1
5
7
14
9
10
12
undefined
13
3
4
2
Explanation:
- First, synchronous code runs.
- Then, promise handlers (microtasks).
- Next, setTimeout with 0 delay (macrotasks), which may contain microtasks.
- Finally, setTimeout with 10 ms delay.