Javascript - Communicating with Generators

Introduction

We can pass a value via yield to the generator function and use those values inside the generator function when the execution resumes.

function *calculator() { 
    const num1 = yield "first"; 
    const num2 = yield "second"; 
    console.log(`Sum is: ${num1 + num2}`); 
} 

const myGenerator = calculator(); 

console.log(myGenerator.next()); 
// { value: 'first', done: false } 

console.log(myGenerator.next(2)); 
// { value: 'second', done: false } 

console.log(myGenerator.next(3)); 
// Sum is: 5 
// { value: undefined, done: true } 

Here, the first time next() was called, the generator yields the "first" string and pauses.

The second time the value from the next(2) will be assigned to num1.

Inside the generator, we specified that whatever value is yielded at yield "first" gets assigned to num1.

Hence, the third time next() was called, Sum is: 5 was printed to the console.

Since there was no more yield statements, undefined was returned as the value.

Related Topic