Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

By what is the suspended execution of context in the eventloop model?

Giving the code instanly:

setTimeout(() => console.log("next macro")); /// next macro
Promise.resolve().then(() => gen.next()) /// microtask inside, #2
const gen = (function*(){
    console.log("Hello");
    yield; /// #3
    console.log("World");
})();
gen.next();
console.log("main script has been ended"); /// #1

As you know generators can be suspended. So later we can back into generator function when some code will invoke certain code that related with generator.

This code has 2 macrotasks and 1 microtask. You know that eventloop won’t execute microtasks till macrotask won’t have been finished. Since when macrotask will have been finished #1, then microtask will be active #2 and exactly code inside this microtask returns us into generator function #3, and we will have executed console.log("World").

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So my question is: by what is the code that executes generator code, resumes and restores the generator execution context? Is it a macro or micro task within the event loop when we invoke it inside a micro task? Is the restored execution context of the generator a microtask, when we are executing it?

P.S You might me not understand because I don’t know how to express my thought properly.

>Solution :

by what is the code that executes generator code, resumes and restores the generator execution context? Is it a macro or micro task within the event loop when we invoke it inside a micro task?

It is executed whenever next() is called on the generator. If that call happens as part of a macro task, it is still part of that macro task. If that call happens as part of a micro task, it is till part of that micro task. The call stack has in fact increased while resuming the generator’s code and returns back to the code that resumed it (as with next()).

Since in your example you call next() both in the synchronous code and in a then callback, it first executes as part of the macro task, and then later as part of a micro task. In that sense it is no different than making a function call.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading