Issue
I have the following set of instructions
console.log(1)
setTimeout(() => {
console.log(3)
});
Promise.resolve().then(() => console.log(4))
console.log(7)
The output is:
1
7
4
3
The order of execution is as follows:
- consoles are executed
- promise resolved
- settimeout executed
Why is the promise resolved before the setTimeout? Both are handled by a callback, right?
Solution
Interesting question. In order to understand the reason, one needs to understand the JavaScript event loop.
.then()
queues a microtask. Microtasks are executed as soon as the JS call stack empties.
In this case (but not in all cases), setTimeout
queues a task in the main task queue. Tasks are queued for external events, timer handlers, rendering (in the browser), etc… If a task calls JS code, the next task will not run until all the microtasks associated with it finish running.
So here’s what’s happening:
- Task #1, queued internally by Node.js:
console.log(1)
logs1
. Output is1
setTimeout(() => { console.log(3) });
queues a task to log3
Promise.resolve().then(() => console.log(4))
queues a microtask to log4
console.log(7)
logs7
. Output is1 7
.- The JS stack empties, because there’s no more statements. The microtasks begin to execute.
- Microtask #1-1, queued by
.then()
:- Logs
4
. Output is1 7 4
.
- Logs
- Microtask #1-1, queued by
- Task #2, queued by
setTimeout()
:- Logs
3
. Output is1 7 4 3
. - The JS stack empties, because there’s no more statements, however there are no microtasks.
Final output:
- Logs
1 7 4 3
Answered By – D. Pardal
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0