JavaScript:使用嵌套生成器中的yield设置值

问题描述 投票:1回答:2
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}

情况正好相反。现在我只能在嵌套生成器中访问屈服值。

有没有办法在这两个生成器之间传递值/结果?

javascript generator yield
2个回答
2
投票

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函数。


0
投票

在使用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

© www.soinside.com 2019 - 2024. All rights reserved.