Today I Learned : Generator Functions
General JavaScript functions can’t be interrupted in the middle of a function execution, once the function is invoked until function execution completes. When we want to execute functions which can be interrupted or which can execute after a while once execution is started then we can use a new type of function called Generator Functions which came into place with ES6.
Fun fact: Async Await is built on top of generator functions
Declaring a generator function
function* generate() {}
“Yield” Keyword introduced in ES6 is used to stop the execution inside the Generator function. It can be used only inside the Generator functions and can’t be used inside the general JavaScript functions.
Generator function will always returns the iterator object, when the iterator calls a “next()” method then the function starts execution till the 1st “yield” statement. The “next()” returns an object with two properties i.e… 1. value (any): The value returned by the function till 1st yield statement. 2. Done (Boolean value): Returns a boolean value true or false which defines whether the function execution is completed or not.
Whenever we use “return” statement in the middle of generator functions, it indicates the function is done with the execution and completed. Whenever we call the next() method it executes the generator function until the 1st yield statement, and later it executes the next yield for every next() method call and continues until all the yield statements are executed.
sample :