Skip to content Skip to sidebar Skip to footer

Restarting A Generator In Javascript

In node (0.11.9, with the --harmony flag), how do I restart a generator after it finishes? I tried doing generator.send(true); but it says the send() method doesn't exists.

Solution 1:

You don't restart a generator. Once it has completed, it has finished its run like any other function. You need to recreate the generator to run again.

var count = function*(){ yield1; return2;};

var gen = count();
var one = gen.next();
var two = gen.next();

// To run it again, you must create another generator:var gen2 = count();

The other option would be to design your generator such that it never finishes, so you can continue calling it forever. Without seeing the code you are talking about, it is hard to make suggestions though.

Solution 2:

A bit late, but this is just a FYI.

At the moment, the send method is not implemented in Node, but is in Nightly (FF) - and only in some way.

Nightly:

If you declare your generator without the *, you'll get an iterator that has a send method:

var g = function() {
  var val = yield1; // this is the way to get what you pass with sendyield val;
}
var it = g();
it.next(); // returns 1, note that it returns the value, not an object
it.send(2); // returns 2

Node & Nightly:

Now, with the real syntax for generators - function*(){} - the iterators you produce won't have a send method. BUT the behavior was actually implemented in the next method. Also, note that it was never intended for send(true); to automatically restart your iterator. You have to test the value returned by yield to manually restart it (see the example in the page you linked). Any value, as long as it's not a falsy one, could work. See for yourself:

var g = function*() {
  var val = 1;
  while(val = yield val);
}
var it = g();
it.next(); // {done:false, value:1}
it.next(true); // {done:false, value:true}
it.next(2); // {done:false, value:2}
it.next(0); // {done:true, value: undefined}

Post a Comment for "Restarting A Generator In Javascript"