Restarting a Generator in Javascript

自闭症网瘾萝莉.ら 提交于 2020-01-03 19:57:08

问题


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.


回答1:


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 = yield 1; // this is the way to get what you pass with send
  yield 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}



回答2:


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*(){ yield 1; return 2;};

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.



来源:https://stackoverflow.com/questions/20890031/restarting-a-generator-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!