Wednesday, February 28, 2018

Javascript Generator Function

Generators are functions which can be exited and later re-entered. The function* declaration defines a generator function, which returns a Generator object.

Calling a generator function does not execute its body immediately; an iterator object for the function is returned instead. When the iterator's next() method is called, the generator function's body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function. The next() method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value as a boolean. Calling the next() method with an argument will resume the generator function execution, replacing the yield expression where execution was paused with the argument from next().

Here is an example of calling generator function.
    function* generator1() {
        yield 1;
        yield 2;
        yield 3;
    }
    var gen1 = generator1();

    let resp = gen1.next();
    console.log('Value-' + resp.value + ": Done-" + resp.done);
    //Response - Value-1: Done-false
    resp = gen1.next();
    console.log('Value-' + resp.value + ": Done-" + resp.done);
    //Response - Value-2: Done-false
    resp = gen1.next();
    console.log('Value-' + resp.value + ": Done-" + resp.done);
    //Response - Value-3 Done-false
    resp = gen1.next();
    console.log('Value-' + resp.value + ": Done-" + resp.done);

    //Response - Value-undefined: Done-true


Here is an example of calling generator function inside generator function.


    function* someFunc(param1) {
        yield "inside someFunc - param1-" + param1;
    }
    function* generator2() {
        yield* someFunc(1);
        yield* someFunc(2);
    }

    var gen2 = generator2();
    console.log(gen2.next().value);
    console.log(gen2.next().value);

No comments: