DEV Community

Cover image for JS interview in 2 minutes / Promise

JS interview in 2 minutes / Promise

Nick K on May 12, 2021

Question: What is a Promise? Quick answer: It is an object which represents the current state and value of the operation. There are three states f...
Collapse
 
_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.

Collapse
 
hexnickk profile image
Nick K

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)
console.log(1)
console.log(2)
Enter fullscreen mode Exit fullscreen mode

will produce output

1
2
3
Enter fullscreen mode Exit fullscreen mode

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

MDN/Even toop

Collapse
 
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)

Collapse
 
firaskh1992 profile image
firas khateeb • Edited

hey Nikita,
Thanks for sharing such a great article,
one more thing I suggest to replace setTimeout with queueMicrotask, since then/catch/finally callbacks is a microTasks and not Tasks as setTimeout callback.

in such a case promises callback will be passed by JS engine into the microTask queue.

Collapse
 
sajjadalidev profile image
Sajjad Ali

Thanks for sharing
::)