【问题标题】:Generator return doesn't work in for-await-of loop生成器返回在 for-await-of 循​​环中不起作用
【发布时间】:2021-08-26 10:41:47
【问题描述】:

带有return 语句的生成器跳过for-await-of 循​​环的执行。

(async () => {
  const gen = async function* () {
     return { newState: "FAILURE" };
  };
  for await (const { newState } of gen()) {
    console.log("Yey! new state is:", newState);
    // do other stuff
  }
})();

在上面写的情况下,整个 for-await-of 构造永远不会 console.log 任何东西。但是,当您将 return 替换为 yield (yield { newState: 'FAILURE' }) 时,一切都会按预期进行。

(async () => {
  const gen = async function* () {
    yield { newState: "FAILURE" };
  };
  for await (const { newState } of gen()) {
    console.log("Yey! new state is:", newState);
    // do other stuff
  }
})();

为什么?

【问题讨论】:

    标签: javascript asynchronous ecmascript-6 generator


    【解决方案1】:

    迭代器在完成之前从未产生任何东西,因此循环没有任何可迭代的东西 - 序列是空的。请注意,您可以yield 多次,但return 只能一次。

    for … of 循环忽略迭代器的 return 值。它仅在您手动推进迭代器或使用 yield* 时有用。

    async function* generate() {
      return { newState: "FAILURE" };
    };
    const generator = (async function*() {
      const { newState } = yield* generate()
      console.log("Yey! new state is:", newState);
      return "some value";
    })();
    generator.next().then(console.log);

    这对于异步迭代器 than for synchronous iterators 没有什么不同。

    【讨论】:

    • 您能否提供一些明确说明/为什么 for-await-of 忽略返回的文档?
    • @Src 它不会忽略 return 语句 - 它会按预期停止。它只是没有任何地方可以放置返回 value - for 循环不是具有结果值的表达式。
    • 根据文档,yield 和 return 都返回值,但 return 而不是 yield 返回 {done:true}。那么为什么在这种情况下它不像收益呢?
    • 还有循环如何知道何时停止,因为如果我们将 return 与 yield 交换,我们仍然会得到正确的结果,考虑到我们没有手动说停止迭代,你通常会这样做返回
    • "return 而不是 yield 返回 {done:true}" - 是的,完全正确。这标志着迭代的结束。不是最后一个值 - 否则你不能有一个空序列。 “为什么它不像 yield” - 因为它是 return,而不是 yield
    猜你喜欢
    • 1970-01-01
    • 2021-07-15
    • 2017-07-11
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 2020-08-21
    • 2017-08-06
    • 2021-09-07
    相关资源
    最近更新 更多