JavaScript 异步生成器函数中的“yield await”是多余的吗?

Is "yield await" redundant in JavaScript async generator functions?

提问人:jmartinezmaes 提问时间:8/31/2023 更新时间:8/31/2023 访问量:56

问:

在将迭代器结果发送给调用方之前,声明中产生的承诺似乎会自动等待(来源:MDN)。这是否意味着这是多余的,并且在所有情况下都会产生相同的行为?或者,是否有需要注意的例外情况?async function*yield await somePromiseyield somePromise

P.S. 我认为可能存在一些与错误处理上下文相关的行为差异。不过,从我的实验来看,似乎在块中产生的承诺将始终在异步生成器中被捕获和处理,无论是否有显式的.try/catchtryawait

JavaScript async-await 生成器 产量

评论

1赞 Bergi 8/31/2023
是的

答:

2赞 Hao Wu 8/31/2023 #1

这里是多余的。使用还会延迟微任务队列中的解析时间。awaitawait

Promise.resolve()
  .then(() => console.log(1))
  .then(() => console.log(2))
  .then(() => console.log(3))
  .then(() => console.log(4))
  .then(() => console.log(5));
  
(async () => {
  const func = async function*() {
    yield await Promise.resolve('yield await');
  };
  
  for await (let i of func()) {
      console.log(i);
  }
})();

Promise.resolve()
  .then(() => console.log(1))
  .then(() => console.log(2))
  .then(() => console.log(3))
  .then(() => console.log(4))
  .then(() => console.log(5));
  
(async () => {
  const func = async function*() {
    yield Promise.resolve('yield');
  };
  
  for await (let i of func()) {
      console.log(i);
  }
})();