Javascript Generators

Generator is a special type of method. This method can be create an objects of generator type. And this object are execute this methods and control their operation. That objects are capable to stop the current execution steps of method using yield statement. The speciality of this method are that can returns multiple value in form of an objects.

Define Generator functions

function * methodName(parms){
  //method statement here
  yield returnValue;
  //method statement
  yield returnValue;
  //:
  //:
  //method statement
}

next() method are used to resume the method instruction.

yield statement are pauses current execution of method and return at least two properties (value and done).

function * testFunction() {
  console.log('\nFirst instruction');
  yield 'Compile The Code';  

  console.log('\nSecond instruction');  
  yield 'Debugging the Code';

}
const generatorObject = testFunction(); 
console.log(generatorObject.next().value); 
console.log("complete First Step");

console.log(generatorObject.next().value); 
console.log("complete Second Step");
Generator functions Execution
First instruction
Compile The Code
complete First Step

Second instruction
Debugging the Code
complete Second Step

Generators are iterable

Generators object is iterable in execution process.

function * testFunction() {
  console.log('\nFirst instruction');
  yield 'Compile The Code';  

  console.log('\nSecond instruction');  
  yield 'Debugging the Code';

  console.log('\nThird instruction');  
  yield 'Runing the Code';
}
const generatorObject = testFunction(); 
var step=1;
for (const val of generatorObject) {
  console.log(val); 
  console.log(`complete Step ${step}`);
  step++;
}
First instruction
Compile The Code
complete Step 1

Second instruction
Debugging the Code
complete Step 2

Third instruction
Runing the Code
complete Step 3


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved