在下面的代码中,为什么第一次调用next()
会返回第二个 yield
关键字之后的值?
function* generatorFunction() {
yield (yield 'the second yield')();
}
function func(x) {
return 'func passed to the second next()';
}
var iterator = generatorFunction();
var firstValue = iterator.next().value;
var secondValue = iterator.next(func).value;
console.log(firstValue); // "the second yield"
console.log(secondValue); // "func passed to the second next()"
在第一个next()
上,它会在第一个yield
作为表达式之后处理剩下的行,对吗?这是否意味着(yield x)()
评估为x,但在评估它时实际上并没有暂停产量?
然后第二次调用next
传递一个函数,该函数取代(yield 'the second yield')
,然后执行,然后返回它的值。
有人可以帮忙解释一下这里发生了什么吗?
BTW这没有用处,我只是通过es6katas。
答案 0 :(得分:1)
这是一个很好的例子,但几乎是自我解释。
表达式
yield (yield 'the second yield')();
根据{{3}},从内到外进行评估。
首先,评估外部yield
的右侧部分(yield 'the second yield')()
。
首先评估左侧功能部件(yield 'the second yield')
组。第'the second yield'
次调用会返回next()
值,生成器会在内部yield
上暂停。
生成器在next(func)
呼叫时恢复,yield 'the second yield'
被评估为发送值(func
),然后右功能部分func()
被评估为'func passed to the second next()'
。
最后,评估外部yield
的左侧部分,从第二次'func passed to the second next()'
调用返回next(func)
,生成器暂停。