为什么第二个在这个生成器中首先产生 return

Why does the second yield return first in this generator

在下面的代码中,为什么 first 调用 next() return second[= 之后的值32=] 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')并因此被执行,然后return它的值。

谁能帮忙解释一下这是怎么回事?

顺便说一句,这没有任何实际意义,我只是在浏览 es6katas

这是一个很好的例子,但几乎不言自明。

表达式

yield (yield 'the second yield')();

根据 operator precedence.

由内而外计算

首先,计算外部 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 的左侧部分,从第二个 next(func) 调用返回 'func passed to the second next()',生成器暂停。