setTimeout(() => console.log("t1"));
Promise.resolve()
.then(() => {
console.log("p1");
setTimeout(() => console.log("t2"));
})
.then(() => console.log("p2"));
queueMicrotask(() => console.log("q"));
p1 q p2 t1 t2
The answer is p1 q p2 t1 t2.
• During the script, p1 and q are queued as microtasks, in that order.
• p2 is queued only when the p1 callback finishes, so it lands after q.
• All microtasks run before any timer.
• Timers run in the order they were scheduled, so t1 comes before t2.
The tempting option "p1 p2 q t1 t2" is wrong because p2 is not queued at the start. Each then is queued only when the step before it finishes.
Read more