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

August 1, 2018

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

https://truetocode.com/understanding-callbacks-and-callback-hell-in-javascript-asynchronous-behavior-of-javascript-part-1/697/

https://truetocode.com/understanding-promises-in-javascript-asynchronous-behavior-of-javascript-part-2/730/

 

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

Genereator Function Prototype

 

 

You can see the next method in the generator function prototype.To get the value of the first yield we use the next() method.

 

 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 an yield

Here you an 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

 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*

2 Comments

Leave a Reply

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