Why Promise is resolved before setTimeout? - Event loop, task queue, micro task queue, stack
Promise.resolve schedules a microtask and the setTimeout schedules a macrotask. And the microtasks are executed before running the next macrotask.
console.log(1) setTimeout(() => { console.log(3) }); Promise.resolve().then(() => console.log(4)) console.log(7)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),
setTimeoutqueues 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 is1setTimeout(() => { console.log(3) });queues a task to log3Promise.resolve().then(() => console.log(4))queues a microtask to log4console.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:
1 7 4 3- Logs
'✘✘✘ Javascript' 카테고리의 다른 글
| Capitalize first letter (0) | 2023.01.09 |
|---|---|
| [Javascript] Promise.allSettled vs Promise.all, Promise (0) | 2023.01.07 |
| [javascript] how to parse string to number, Number, parseInt, + (0) | 2022.07.12 |
| [javascript] IIFE(immediately invoked function expression) (0) | 2022.07.12 |
| [javascript][event] Detect mouse right click: context menu (0) | 2022.07.05 |
댓글