TIL : 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 :
// A simple generator function that demonstrates how generators yield values
// and how execution can pause and resume between yields.
function* generator(i) {
// The first yield immediately returns the initial value of i
yield i;
console.log('first console i:', i);
// The second yield adds 10 to i
yield i + 10;
console.log('second console');
// The generator returns 15. After this return, the generator is considered done.
return 15;
// Even though we wrote another yield here, it will never execute because the return statement above ends the generator.
yield i + 20;
}
// Create a generator instance, passing in the initial value 6
const gen = generator(6);
// Each .next() call continues the generator until the next yield (or return)
// 1) Returns { value: 6, done: false }
// The generator "paused" right at yield i;
console.log(gen.next());
// 2) Logs 'first console i: 6' then returns { value: 16, done: false }
// The generator "paused" at yield i + 10;
console.log(gen.next());
// 3) Logs 'second console' then returns { value: 15, done: true }
// The generator is now done because of the return 15 statement.
console.log(gen.next());
// 4) Now that the generator is finished, subsequent calls return { value: undefined, done: true }
console.log(gen.next());
console.log(gen.next());
Subscribe to my newsletter
Read articles from Shaurya Kalia directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
