Guess the output #1
Question:
const promise = new Promise((resolve, reject) => {
console.log(1);
setTimeout(() => {
console.log("timerStart");
resolve("success");
console.log("timerEnd");
}, 0);
console.log(2);
});
promise.then((res) => {
console.log(res);
});
console.log(4);
Output:
1
2
4
timerStart
timerEnd
success
Explanation:
- Immediate Execution:
- console.log(1) is executed, printing 1.
- console.log(2) is executed, printing 2.
- Promise Creation:
- A Promise is created, but it doesn't resolve immediately. The setTimeout function schedules the callback to run after 0 milliseconds (as soon as possible, but after the current execution stack is cleared).
- Synchronous Code Continues:
- console.log(4) is executed, printing 4.
- Event Loop & Microtask Queue:
- After the synchronous code execution finishes, the event loop picks up the callback from setTimeout. This prints timerStart.
- The resolve("success") call is executed, but the then callback is queued in the microtask queue.
- console.log("timerEnd") is executed, printing timerEnd.
- Microtask Execution:
- The event loop then processes the microtask queue, where the then callback is executed, printing success.