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

时间:2017-12-19 23:43:22

标签: javascript generator yield

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}

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

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

2 个答案:

答案 0 :(得分: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函数。

答案 1 :(得分:0)

在使用javascript中的新yield升级自己并尝试阅读您的示例后,我想我已经弄清楚您要做什么以及您做错了什么。

您的第一次尝试是正确的。但是你错误地将你的console.log放错了,误导你认为这是错误的。

我重新编写了这篇文章,以便您更好地了解yield时的情况。

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