More on Generator Objects


Sending input using next()

In addition to iterating through Generator Objects, next() can also be used to send values back into Generator functions. This is accomplished by passing a value into the next() method call as an argument. The value that is passed into the next() method call eventually becomes the return value of the most recent yield statement. Since the first next() call starts the Generator function, any value that gets passed into it will be ignored.


Notice how the next() method call is used to send values back into the Generator function:

function* genFunc(){
    let a = yield;
    console.log(a); //a = 1
    let b = yield;  
    console.log(b); //b = 2
    let c = yield;
    console.log(c); //c = 3

}

let genObject = genFunc();

genObject.next(0); //starts genFunc(), the value inside the next() call is ignored
genObject.next(1); //sends a value of 1 to genFunc()
genObject.next(2); //sends a value of 2 to genFunc()
genObject.next(3); //sends a value of 3 to genFunc()
genObject.next(4); //the value inside next() is ignored because genFunc() has no more yields


The next() method can also be used to modify the values sent by the yield statement and send them back.

Notice how the next() method is used to obtain values from yield, modify them, and then send them back:

function* genFunc(){
    let a = yield 'a';
    console.log(a); // a = 'a!'
    let b = yield 'b';  
    console.log(b); // b = 'B'
    let c = yield 'c';
    console.log(c); // c = 'abc'

}

let genObject = genFunc();

let w = genObject.next(); //starts genFunc(), w = Object {value: 'a', done: false}
let x = genObject.next(w.value + '!'); //sends a value of "a!" to genFunc(), x = Object {value: 'b', done: false}
let y = genObject.next(x.value.toUpperCase()); //sends a value of 'B' to genFunc(), y = Object {value: 'c', done: false}
let z = genObject.next(w.value + x.value + y.value); //sends a value of 'abc' to genFunc(), z = Object {value: 'undefined', done: true}

results matching ""

    No results matching ""