Yan*_*hon 1 ecmascript-harmony
考虑这段代码:
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));
Run Code Online (Sandbox Code Playgroud)
和输出
#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 }
Run Code Online (Sandbox Code Playgroud)
为什么第一次调用it.next()完全跳过参数(在上面的代码中"bar")?或者,换句话说,为什么后续调用的行为会有所不同?我希望调用生成器函数会跳过参数,并且调用next()实际上会初始化迭代器,使过程更加连贯,不是吗?
草案中:
经过更多研究后,答案就在 Harmony 的草案中(参见 wiki: http: //wiki.ecmascript.org/doku.php? id=harmony:generators# methodnext)。
next应该没有争论。然而,用一个参数调用似乎与用一个参数next调用是等价的send。答案就在这里。send被设计为如果首先调用(没有事先)则抛出错误next。
所以基本上,您不应该能够通过传递参数来“初始化”迭代器,因为next您无权这样做。
在实现中:
然而,这只是规范。总结一下作为评论所说的内容,至少有两个原因导致您无法将参数传递给第一个参数next而必须将其传递给生成器。
第一个事实是您需要某种方法来实际获得这个参数。您不能像下次通话时那样进行操作let myVar = yield myValue。
第二个是next只接受一个参数,这是相当有限的,而您可以在生成迭代器时将无限数量的参数传递给生成器。
然而,这只是目前正在发生的事情。没有任何内容表明草案或实施不会改变。我们当然可以想象send接受任意数量的参数(没有理由,但是嘿,谁知道),并能够将其转换为生成器的参数。管他呢。