Generator Function

2019-06-25

Generator function is a new feature in ES6, it is not like a normal function, with generator function we can control (pause, stop, resume) the execution process inside it. I will give comparison between those two to explain how generator function works.

The code below is a normal function:

function add(a, b) {
  console.log('Start adding two numbers');
  const result = a + b;
  console.log('The result is : ' + result);
  console.log('End of function');
}

With generator function, we can write the code above into this:

function* add(a, b) {
  yield console.log('Start adding two numbers');
  const result = a + b;
  yield console.log('The result is : ' + result);
  yield console.log('End of function');
}

and then we execute that function like so:

var gen = add(2,3)

This will not give any results yet, because this add function is a generator and is now in pause, to continue executing the function, we need to use next()

gen.next()

The first we use next() will give result in console:

Start adding two numbers
{value: undefined, done: false}

That done: false means that this generator function is not finished yet, there is more to it, so we can use next() again

The second next() will give result:

The result is : 5
{value: undefined, done: false}

The third next() will give result:

End of function
{value: undefined, done: false}

The fourth next() will give result:

{value: undefined, done: true}

Now the generator function has reached its end of execution process, the value is undefined because we did not return anything.

As you can see, generator is very powerful, we can pause the execution process as it deals with other things, and then come back to it and resume the execution later.