Sunday, September 9, 2018

Es6 Generator Functions Yield in javascript | Typescript | examples

In this blog post, We are going to learn Generator Functions and Yield Keyword with examples.
First We will see how Normal Function works? Normal Functions are called, executes it and the function returns finally either return the value of function body execution is completed. Function Example here is a function example, When function Method is called, Sequence of statements in a body executed, finally returned value and iteration is stopped its control.
function method(){
//body
return value;
}

method();

Generator Function Introduction 

The generator is a special kind of Functions that introduced in ES6- ES2015. These functions control the how we want to iterate behavior. when The function is called, It can be paused and resumed. Example Here is an example of Generator Functions
function* generateFunctions() { 
    console.log('Generateor Function started');
    yield 'pause';
    console.log('Generateor Function Completed');
}
const gfunctions=generateFunctions();
console.log(gfunctions.next());
console.log(gfunctions.next());
console.log(gfunctions.next());
Output is
[object Generator]
"Generateor Function started"
Object { value: "pause", done: false }
"Generateor Function Completed"
Object { value: undefined, done: true }
Object { value: undefined, done: true }
We will see the difference between Normal Function and Generator Function 

  • This function starts with function* and normal function starts with function 
  • Function execution paused using yield keyword when the below statement executes, the function is not called, It gets the generator function object.
const gfunctions=generateFunctions();
Initially, Function is not called and suspended, You have to call gfunctions.next() to call function body. next() method returns an object which contains value and done keys. Each time when you called next() method, function resumes its execution and return an object which contains and value and done keys
value: It is the output of yield code execution
done:- status of the execution, false means function execution is not completed

Typescript Function Generator 

When you generator function in typescript, It will no work default and gives the following error TS2339: Property 'next' does not exist on type You have to make configuration changes to tsconfig.json file and fix for the above error is
"target": "es6",
"lib": [
    "es6"
]
Typescript Yield keyword
Typescript supports generator functions and behavior works as expected

Related article


EmoticonEmoticon