JS Generator Functions
Introduction
Generator functions are special type of functions which have the ability to return from a checkpoint and then begin execution from the same point . We can have multiple checkpoints in a generator function. Syntax:-
function* functionName()
{
//function logic
}
The asterik(*) sign that you can observe after function keyword separates it from a normal function.
Example of a generator function & its usage:-
Edit/view code:- Online Code
Generator Object
When we call a generator function an object is returned by it which is called Generator Object. It complies with both iterable and iterator protocols.
- Iterator protocol defines a standard way to produce a sequence of values. An object is an iterator when it implements a
next()
method. - Iterable protocol allows object to define or customize their iteration behavior, such as what values are looped over in a
for...of
construct.
Structure of a generator object looks like below:-
Next Method
Next method of an generator object of a generator function will execute the code up to the next yield keyword encountered. Yield keyword in generator functions acts as checkpoint. A generator function can have multiple yield.
Next method upon execution returns an object with two properties:-
- value:- It contains the value returned by the yield statement.
- done:- It tells if the generator function has reached at the end or not. If it is true then generator function has reached its end.
Example:- {value:10, done: false}
Return & Throw methods
return:- When we call return method it will finish the execution of generator function and return the following:-
{value: undefined, done: true}
throw :- This method can be used to throw an exception manually which will be handled if generator function has a catch part and returns next value.
Following is another example of generator function’s working with rest api data handling :-
Edit/View code :- Online code