考虑这段代码:
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()
实际上会初始化迭代器,使过程更加连贯,不是吗?