Javascript Generator yield statement

Introduction

The yield keyword can pause a function as it is running.

This is very similar to the return keyword.

When using return, the function is executed and the final value is returned to the caller.

When using yield, the function can be executed again.

When the function is paused using yield it cannot be restarted on its own.

In order to restart the function, the iterator method next() must be called.

In every instance, an object is returned with two properties.

The done property will have a value of false, letting you know that you can run the next() method and continue using that function.

The value property will return whatever value is being returned from the yield keyword.

function fun1(){ 
     console.log('function 1'); 
} 
function fun2(){ 
     console.log('function 2'); 
} 

function *runFun(){ 
     yield; //  w  w w .j ava 2  s  .c o  m
     yield fun1(); 
     yield fun2(); 
} 
let iterator = runFun(); 
console.log(iterator.next()); //pauses function  Object {value: undefined, done: false} 
console.log(iterator.next()); //returns 'function1' Object {value: undefined, done: false} 
console.log(iterator.next()); //returns 'function 2' Object {value: undefined, done: false} 
console.log(iterator.next()); //done = true Object {value: undefined, done: true} 



PreviousNext

Related