0

While executing the below code I got the output as:

1
4
3
undefined
2

console.log(1)
setTimeout(() => {
console.log(2)
});
Promise.resolve().then(() => 
console.log(3)
)
console.log(4)

I understand that the micro queue task is executed after the synchronous task completed in the stack and after the execution of micro task(promise call) stack will be empty, the macro task will occupy the stack and will be executed and the stack gets empty. If I am correct output will be:

1
4
3
2

I don't know why undefined is present while execution moves from micro task to macro task.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

I guess that you are running the script in the debug-tools console. This will explain the undefined. That because debug-tools console will return the result of the last command (console.log in your case).

This is how the code really runs: https://codesandbox.io/s/sharp-neumann-xwbut?fontsize=14&hidenavigation=1&theme=dark

Daniel
  • 2,288
  • 1
  • 14
  • 22