在发电机内部的发电机上调用next()

时间:2017-01-16 23:00:08

标签: javascript ecmascript-6

let gen = testGenerator(),
    foo = true;

console.log( gen.next().value ); //logs 1
console.log( gen.next().value ); // throws 'Uncaught Error: Generator is already running'

function *testGenerator(){
    yield 1;
    if(foo) gen.next(); //I want to immediately advance the generator after the 'yield 2' and run again to 'yield 3'
    yield 2;
    console.log('bar')
    yield 3;
}

我希望能够根据生成器运行时遇到的某些逻辑将JS生成器推进到下一阶段(在此示例中,'foo'是否为真,'yield 1'和'yield 2'之间)。

我理解为什么这段代码不起作用(我不能在生成器运行完毕之前调用'gen.next()'),但我想知道是否还有立即调用“下一步”的步骤发电机内部的发电机。

1 个答案:

答案 0 :(得分:3)

如果foo不为真,你可以简单地重写逻辑以仅执行第二次收益。 https://jsfiddle.net/xnxxs20u/

 function *testGenerator(){
    yield 1;
    if(!foo) yield 2;        
    console.log('bar')
    yield 3;
}
相关问题