1

Let say we have the following snippet. Can someone explain what you expect to print out and why?

setTimeout(() => {
    console.log("check 00");
}, 0);

new Promise((resolve, reject)=>{
    console.log("check 01");
    resolve();
}).then(()=>{
    console.log("check 02");
})

console.log("check 03");

By running in the terminal, I got the following output.

check 01
check 03
check 02
check 00

I understand check 01 will be printed out first because Promise executor function is executed immediately by the Promise implementation. Then we have check 03 because of JS's run-to-completion scheduling.

But what about check 02 and check 00?

hackjutsu
  • 8,336
  • 13
  • 47
  • 87
  • setTimeout gets pushed to end of stack. Also `0` is not really accurate...there is a minimum delay – charlietfl May 23 '17 at 21:50
  • 1
    Also: [Why does Promise.then 'onFulfilled' function fire before setTimeout callback?](https://stackoverflow.com/q/42800326/1048572) – Bergi May 23 '17 at 21:51
  • @charlietfl But so do `then` callbacks. – Bergi May 23 '17 at 21:51
  • OK, I get it. The `Promise.then()` is added to the microtask queue, while `setTimeout()` is added to the normal task queue. The microtask queue will be executed and cleaned up right after the current task is finished and before the next task is picked up (next tick). – hackjutsu May 23 '17 at 23:37

0 Answers0