Generator Functions in JavaScript : asynchronous behaviour of Javascript Part -3

For part 1 and part 2 of this series, see the following links




JavaScript version ES6/ES2017, a new kind of function called generator functions was introduced. These special functions help you to manage asynchronous operations with more ease. Generator functions can be paused and then continued. Generator functions are declared with an asterisk (*) and have a yield keyword which yields data. See the following example to see the proper syntax for using Generator functions.


Genereator Function Prototype

There is a next method in the generator function prototype. To get the value of the first yield we use the next() method.



Here you can see that the response object has a key-value which gives the value of the yield and a done key which represents the status. Here in our example,  value will be 1 and done will be false.
We have two yields in the generator function .next() gives false two times and a third time gives done as true. If you add a return to the generator function next() will have key done as true.





Now, if a return is done before a yield

Here you can see that the second yield will have value undefined.
Now we can use Generator functions with asynchronous operations. Here the generator function calls another generator function from within.



Asynchronous operations in generator functions

Providing argument to the next() method. We provide string ‘three’ for the next method which will be the return value of the yield.


Using generator functions in a loop. Here you can see that the generator function yields each item in the loop one by one on each call of the next() method




Leave a Reply

Your email address will not be published. Required fields are marked *