function* test(action) {
const subgenerator = function*() {
const subgeneratorVariable = yield '1';
console.log('subgeneratorVariable', subgeneratorVariable);
};
for (const generatedValue of subgenerator()) {
const result = yield generatedValue;
console.log('result', result);
}
}
const gen = test();
console.log(gen.next());
console.log(gen.next('a'));
返回:
{value: "1", done: false}
result a
subgeneratorVariable undefined
{value: undefined, done: true}
所以我无权访问嵌套生成器中的结果。然而!
在这种情况下:
function* test(action) {
const subgenerator = function*() {
const subgeneratorVariable = yield '1';
console.log('subgeneratorVariable', subgeneratorVariable);
const subgeneratorVariable2 = yield '2';
console.log('subgeneratorVariable2', subgeneratorVariable2);
};
const result = yield* subgenerator();
console.log('result', result);
}
const gen = test();
console.log(gen.next());
console.log(gen.next('1'));
console.log(gen.next('2'));
结果是:
{value: "1", done: false}
subgeneratorVariable a
{value: "2", done: false}
subgeneratorVariable2 b
result undefined
{value: undefined, done: true}
情况正好相反。现在我只能在嵌套生成器中访问屈服值。
有没有办法在这两个生成器之间传递值/结果?
yield
将返回你传递给next
的参数,而不是右边的表达; for...of
内部调用没有参数的next
所以你得到undefined
。
也许这个例子可以帮助你理解do...while
而不是for...of
:
function* test(action) {
const subgenerator = function*() {
let subgeneratorVariable;
subgeneratorVariable = yield '1';
console.log("subgeneratorVariable: " + subgeneratorVariable);
subgeneratorVariable = yield '2';
console.log("subgeneratorVariable: " + subgeneratorVariable);
};
const sub = subgenerator();
let value;
do {
value = yield sub.next(value).value;
console.log("value: " + value);
} while(value);
}
const gen = test();
let value;
value = gen.next().value;
value = gen.next(value).value;
value = gen.next(value).value;
结果是:
value: 1
subgeneratorVariable: 1
value: 2
subgeneratorVariable: 2
如您所见,如果要保留生成器之间的值,则必须将结果值传递给生成器next
函数。
在使用javascript中的新yield
升级自己以及阅读您的示例后,我想我想出了您要做的事情以及您做错了什么。
你的第一次尝试是正确的。但你错误地放置了你的console.log
误导你认为这是错误的。
我重写了它,以便您更好地了解当yield
-ing时会发生什么。
function* generator() {
function* subgenerator() {
yield '1';
yield '2';
};
for (let generatedValue of subgenerator()) {
// Use generatedValue here ...
console.log("Inside generator:",generatedValue);
// .. and finally yield it to your main program
yield generatedValue;
}
}
let gen = generator();
console.log("Outside generator:",gen.next());
console.log("Outside generator:",gen.next());
console.log("Outside generator:",gen.next());
在第二个示例中,您将生成委托给子生成器。这样做,您无法获得发电机本身的价值。因为该值是yield
-ed并且您的发电机将在子发电机完成生成后恢复。它解释了为什么,你的发电机只看到undefined
。