Now put on your thinking hats and think what output of above code snippet would be.
The correct answer goes as
- call the printer
- Inside the Printer
- Promise resolved
- Timeout 1
Actually when the printer function is called the Inside the Printer is logged. Now the important thing to note here is that even when the timer is set to 0 the log statement inside setTimeout() is executed after promise is resolved. To understand this you need to know how the event loop handles tasks and microtasks. The event loop runs continuously and ensures that all the tasks queued are executed sequentially. So in our case the setTimeout() is scheduled as a task which is executed in the next event loop. But the question here remains is How the hell does Promise log the statement first?
The crux is -:
- Tasks have to wait for next round of execution
- Microtasks can execute in the same round after the current script finishes execution
Hopefully I could explain the topic in a simple yet effective manner. Bye !!!