Javascript Generator Introduction

Introduction

Generators are functions that do not immediately execute when called on.

They return an iterator object that you can call and pass parameters at another time.

You can continue to call this function until the first yield expression is executed.

Creating a Generator

function * helloGenerator(){ 
   yield 'HI'; /*from   www.ja  v  a 2  s  .c om*/
} 

let sayHello = helloGenerator(); 

console.log(sayHello) //returns generator 
//console.log(sayHello.next()) //returns Object 
console.log(sayHello.next().value)  //yield returns HELLOFRIEND 
console.log(sayHello.next().value) //returns undefined 

Iterators execute the function by using the next method.

What is returned is an object that has two values: done and value.

The first done will have a value of true if the iterator has reached the end and there are no more results to return.

It will be false if it can produce more values.

The second value called value returns any value from the iterator until undefined is returned.

function * helloGenerator(){ 
   yield 'HI'; /* ww w.j a v  a  2 s  . c  o m*/
} 

let sayHello = helloGenerator(); 

console.log(sayHello) //returns generator 
console.log(sayHello.next()) //returns Object 
console.log(sayHello.next()) //returns Object



PreviousNext

Related