Home > Software design >  By what is the suspended execution of context in the eventloop model?
By what is the suspended execution of context in the eventloop model?

Time:12-06

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
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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").

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.

CodePudding user response:

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.

  • Related