重新启动Javascript生成器 [英] Restarting a Generator in Javascript
问题描述
在节点(0.11.9,带有--harmony
标志)中,如何在生成器完成后重新启动它?
In node (0.11.9, with the --harmony
flag), how do I restart a generator after it finishes?
我尝试做generator.send(true);
,但是它说send()方法不存在.
I tried doing generator.send(true);
but it says the send() method doesn't exists.
推荐答案
有点晚了,但这只是仅供参考.
A bit late, but this is just a FYI.
目前,send
方法尚未在Node中实现,而是在Nightly(FF)中实现,并且仅以某种方式实现.
At the moment, the send
method is not implemented in Node, but is in Nightly (FF) - and only in some way.
晚上:
如果您声明的生成器不带,则您将获得一个具有send
方法的迭代器:
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
节点&每晚:
现在,使用生成器的真实语法-function*(){}
-您生成的迭代器将没有send
方法.但是该行为实际上是在next
方法中实现的.另外,请注意,send(true);
从未打算自动重新启动迭代器.您必须测试yield
返回的值才能手动重新启动它(请参见链接页面中的示例).只要不是 fassy 值,任何值都可以使用.亲自看看:
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}
这篇关于重新启动Javascript生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!