Why is a promise resolved before a setTimeout


I have the following set of instructions

setTimeout(() => {
Promise.resolve().then(() => console.log(4))

The output is:


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?


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:

  1. Task #1, queued internally by Node.js:
    1. console.log(1) logs 1. Output is 1
    2. setTimeout(() => { console.log(3) }); queues a task to log 3
    3. Promise.resolve().then(() => console.log(4)) queues a microtask to log 4
    4. console.log(7) logs 7. Output is 1 7.
    5. The JS stack empties, because there’s no more statements. The microtasks begin to execute.
      1. Microtask #1-1, queued by .then():
        1. Logs 4. Output is 1 7 4.
  2. Task #2, queued by setTimeout():
    1. Logs 3. Output is 1 7 4 3.
    2. The JS stack empties, because there’s no more statements, however there are no microtasks.
      Final output:

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

Leave a Reply

(*) Required, Your email will not be published