迭代返回Generator的Generator

Iterate over Generator which returns a Generator

本文关键字:Generator 返回 迭代      更新时间:2023-09-26

我试着去理解generator,但是我发现了一个我无法遵循的例子。

// First Generator
function* Colors ()
{
  yield "blue";
  yield* MoreColors ();
  yield "green";
 }
// Generator refered by the first Generator
function* MoreColors ()
{
  yield "yellow";
  yield "orange";
 }
// Let us iterate over the first Generator
const colorIterator = Colors();
let color;
while (!(color = colorIterator.next()).done)
{
  console.log(color.value);
}

输出为:"蓝色"黄色"橙色"绿色"

我预期:"蓝色"黄色"橙色"

为什么我期望这个:我认为在橙色返回后,方法.next()在迭代器上从MoreColors ()调用。对于属性.done,这应该返回一个属性值为true的对象。这样,item等于true, while循环应该停止。

显然,我的期望是错误的。

如果有人能指出我的错误,我会很高兴的。

问题是生成器的颜色不会停止一旦MoreColors停止。在MoreColors完成后,Colors的执行将从它停止的地方继续,因此它将在完成之前返回"绿色"。这是因为生成器没有"变成"MoreColors,而是返回它的答案,并且.next()方法仍然在Colors上被调用。