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
Define Generator functions
function * methodName(parms){
//method statement here
yield returnValue;
//method statement
yield returnValue;
//:
//:
//method statement
}
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");

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