node.js - Restarting a Generator in Javascript - Stack Overflow

In node (0.11.9, with the --harmony flag), how do I restart a generator after it finishes?I tried doing

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.

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.

Share asked Jan 2, 2014 at 19:10 Alix AxelAlix Axel 155k99 gold badges404 silver badges507 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You don't restart a generator. Once it has pleted, 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.

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}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744816357a4595350.html

相关推荐

  • node.js - Restarting a Generator in Javascript - Stack Overflow

    In node (0.11.9, with the --harmony flag), how do I restart a generator after it finishes?I tried doing

    2天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信