-1

As per my knowledge async code is executed when the call stack is empty and execution of the async code is finished in web API

  • But In a given code why my async code which is setTimeout function and Promise which resolve quickly -- is not getting executed at the mark point <---

  • at this point call stack is also empty and async code might also have been executed

  • Function fu() is used as a delay so that async code should executed until<----

but output is

after 1 
after 1
Test End
Resolve promise1
0 sec timer

console.log('test start');
setTimeout(() => console.log('0 sec timer'), 0);
Promise.resolve('Resolve promise1').then(res => {
  mk = 20;
  console.log(res);
});
fu();
fu();
// <<---------  
console.log('Test End');

As I am in learning stage of JavaScript so please tell me if I am lagging in tech detail of asynchronous js

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • The code shown is producing errors, and not producing the output described. Can you update the code to a runnable [mcve] which demonstrates the problem? It's not clear to me what you're asking, or what "empty call stack" you're talking about. – David Jul 20 '22 at 11:47
  • Than you very much David for your reply , My doubt is cleared by Bergi's answer – MohishKhadse55 Jul 20 '22 at 15:17
  • that error is due to `mk=20` cause this code is just snippet of my whole code `mk` is not declared in the snippet so you can remove that line .. so code will not generate error – MohishKhadse55 Jul 20 '22 at 15:23
  • Simply executing the above code snippet will readily demonstrate that to not be the case. In the above code snippet, and in any code you write, you are highly encouraged to actually test the code and observe the results, rather than simply read the code and assume the results. It's great that the answer below helped you, and the assertions made in that answer are indeed correct. But as general advice, testing code and observing the results is *very helpful* for you. – David Jul 20 '22 at 15:32

1 Answers1

1

No, the call stack is not yet empty at the point you marked. It still contains the global execution context that is running your <script>. Every script or module is executed in one go, synchronously without interruption, just like you would expect it for the execution of a dom event listener or setTimeout callback or promise then handler.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • ok so event loop also consider the global execution context which is in stack and wait for the complete empty stack.. I thought that `event loop ` might consider global execution context as a default entry in stack ... Thank you very much Bergi – MohishKhadse55 Jul 20 '22 at 15:12