Introduction to ES6 generators

Datetime:2016-08-22 21:36:25          Topic: ECMAScript           Share

August 01, 2016 - Arbaaz

Generatorsin JavaScript are the functions that can be paused and resumed .

function* genFunc(){...}

Calling genFunc() doesn’t execute the body of the function.

const genObj = genFunc();

Instead, it returns generator object which can be used to control the execution of the generator.

genObj.next() will start executing the function and it will execute till it reaches yield keyword.

We can think of yield as return for now . It is similar to C# yield .

function* genFunc(){
  console.log('First');
  yield;
  console.log('Second');
}
const genObj = genFunc();
genObj.next();

/*
output

First
*/

Calling genObj.next() again will resume the further execution after yield.

function* genFunc(){
  console.log('First');
  yield;
  console.log('Second');
}
const genObj = genFunc();
genObj.next();
genObj.next();

/*
output

First
Second
*/

Here’s how the execution looks like:

yield is not allowed inside non-generator functions. That is, yielding in callbacks doesn’t work.

We can also pass the data to generator function via next .

function* genFunc(){
  console.log('First');
  const input = yield;
  console.log(input);
  console.log('Second');
}
const genObj = genFunc();
genObj.next();
genObj.next('Third');

/*
output

First
Third
Second
*/

We can retrieve the yielded values via the generator object genObj :

function* genFunc(){
  console.log('First');
  const input = yield;
  console.log(input);
  console.log('Second');
  yield 'Forth';
}
const genObj = genFunc();
genObj.next();
const result = genObj.next('Third');
console.log(result);

/*
output

First
Third
Second
{
  done: false,
  value: "Forth"
}
*/

We can have multiple yield in the function as shown in the above example.

Once, the execution of the generator function is completed, further calls to genObj.next() will have no effect .

Further reading:





About List