考虑这段代码:
function foo(a) {
console.log("Mul =", a);
return a * 2;
};
function * process(start) {
// next() #1
var result = start;
console.log("Pre-processing =", result);
result = yield foo(result);
// next() #2
console.log("Process result 1 =", result);
result = yield foo(result);
// next() #3
console.log("Process result 2 =", result);
result = yield foo(result);
// next() #4
console.log("Process result 3 =", result);
return foo(result);
}
var it = process(1);
console.log("#1");
console.log("Next 1 =", /*#1*/it.next("bar"));
console.log("#2");
console.log("Next 2 =", /*#2*/it.next(3));
console.log("#3");
console.log("Next 3 =", /*#3*/it.next(7));
console.log("#4");
console.log("Next 4 =", /*#4*/it.next(15));
和输出
#1
Pre-processing = 1
Mul = 1
Next 1 = { value: 2, done: false }
#2
Process result 1 = 3
Mul = 3
Next 2 = { value: 6, done: false }
#3
Process result 2 = 7
Mul = 7
Next 3 = { value: 14, done: false }
#4
Process result 3 = 15
Mul = 15
Next 4 = { value: 30, done: true }
为什么第一个电话是it.next()
跳过参数(在上面的代码中,"bar"
)总共?或者,换句话说,为什么后续调用的行为会有所不同?我期望调用生成器函数会跳过参数,并且调用next()
实际上会初始化迭代器,使过程更加连贯,不是吗?
草案中:
经过更多研究后,答案就在 Harmony 的草案中(参见 wiki:http://wiki.ecmascript.org/doku.php?id=harmony:generators#methodnext).
next
应该没有争论。然而,似乎在呼唤next
有一个参数就相当于调用send
有一个论点。答案就在这里。send
被设计为如果首先调用则抛出错误(不next
prior).
所以基本上,你不应该能够通过传递参数来“初始化”你的迭代器next
因为您无权这样做。
在实现中:
然而,这只是规范。总结一下作为评论所说的内容,至少有两个原因导致您无法将论点传递给您的第一个next
并且必须将其传递给您的生成器。
第一个事实是您需要某种方法来实际获得这个参数。您不能像下次通话时那样进行操作let myVar = yield myValue
.
第二个是next
只接受一个参数,这是相当有限的,而在生成迭代器时,您可以将无限数量的参数传递给生成器。
然而,这只是目前正在发生的事情。没有任何内容表明草案或实施不会改变。我们当然可以想象send
接受任意数量的参数(没有原因,但嘿,谁知道),并能够将其转换为生成器的参数。管他呢。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)