Yielding to a yield

Yielding is not necessarily a shift of control in just one direction. You can use a generator as a data consumer or observer. In such scenarios, when a caller requests the next yielded value by calling iterable.next()it can optionally pass an argument to this next() method. Whatever value is passed will then cause the yield expression within the generator to evaluate to that value.

This is more easily explained with an example. Here, we have created a generator that consumes numbers and yields the sum of all numbers previously consumed:

function* createAdder() {
let n = 0;
while (true) n += yield n;
}

const adder = createAdder();

adder.next(); // Initialize (kick things off!)

adder.next(100).value; // => 100
adder.next(100).value; // => 200
adder.next(150).value; // => 350

Here, we are using the return value of our yield expression (yield n) and then adding it to the existing value of n on each run of the generator. We need to call next() once initially to kick things off as, before this, the n += yield n expression has not been run and is hence is not waiting for a next() call yet.  

Using generators as consumers does not have many use cases and can be quite an awkward pattern to employ since we must use the designated next() method to pass in data. It is, however, useful to know about the flexibility of the yield expression since you may encounter it in the wild.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.38.253