Javascript Generator create

Introduction

Generator functions are defined using the function keyword with an * (asterisk) or using a GeneratorFunction constructor.

The following code uses an * (asterisk).

function *myGen(){ 
     yield 'generator function' 
} 
let iterator = myGen(); 
console.log(iterator.next()); //Object {value: "generator function", done: false} 
console.log(iterator.next()); //Object {value: undefined, done: true} 

Using a GeneratorFunction

let GeneratorFunction = Object.getPrototypeOf(function*(){}).constructor 
let myGenFunction = new GeneratorFunction('value',   'yield value'); 
let myGenIterator = myGenFunction(); 
console.log(myGenIterator.next()); //Object {value: undefined, done: false} 
console.log(myGenIterator.next()); //Object {value: undefined, done: true} 

There are two ways to create a generator function.

Using the function keyword with the * (asterisk) is the best way to create one.

The other way is to use the Object.getPrototypeOf method.

This will return the constructor of the GeneratorFunction.

function* generate() {
    console.log('Start');
    yield;//w w w. j  a v  a 2s.c o  m
    console.log('Finish');
}

let iterator = generate();
console.log(iterator.next());
console.log(iterator.next());



PreviousNext

Related