DEV Community

Discussion on: JS interview in 2 minutes / Promise

_bkeren profile image

I have a question.

How do onResolve , onReject and onFinal methods at the constructor wait for all 'then' or 'catch' methods to be called ? You set the timeout to 0 and invoke 'func', 0 means run the code immediately.

markiewiczjulian profile image
Julian Markiewicz • Edited

not precisely it means "run code in 0 seconds or more". This is because when running code with settimeout this is handled by timer API. Timer API waits given time (here 0 seconds) and then puts function (code that was contained within settimeout) in the message queue. Elements from message queue are run only if event stack is empty (this is far more complex than that and to get it I'm recommending this talk, guy does great job at explaining the event loop and js execution). This is why settimeout is sometimes used as an hack to run our code after call stack is empty (running currently functions ended the execution)

kozlovzxc profile image
Nikita Kozlov Author

Hey 👋 Great question!

For example, if you use setTimeout, your function will be put into the execution queue, but not executed right away.

setTimeout(() => console.log(3), 0)
Enter fullscreen mode Exit fullscreen mode

will produce output

Enter fullscreen mode Exit fullscreen mode

even though console.log(3) appears before console.log(1) and console.log(2).

MDN/Even toop