You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在for await迭代中调用next()并向内层异步生成器传值?

如何在async生成器间通过yield双向传值?

首先明确:for await...of语法无法直接实现向被迭代的生成器传值,因为它的作用是自动消费生成器的输出,每次自动调用next()时不会传入自定义值(第一次调用不传值,后续默认传undefined)。

如果要实现外层生成器gen向内层innerGen的yield传值,必须手动控制迭代器的next()调用,而非依赖for await...of。具体实现如下:

async function *innerGen(){
  let i = 0;
  while (true){
    i = (yield i); // 接收调用者传入的下一个值
  }
}

async function *gen(){
  const innerIterator = innerGen();
  // 首次调用next()启动内层生成器,无需传值
  let innerResult = await innerIterator.next();
  
  while (!innerResult.done) {
    // 将内层生成器产出的值向外传递,同时接收外部传入的新值
    const inputValue = yield innerResult.value;
    // 把外部传入的值传给内层生成器的next()
    innerResult = await innerIterator.next(inputValue);
  }
}

代码说明:

  1. 手动获取innerGen的迭代器,避开for await的自动迭代逻辑;
  2. 第一次调用innerIterator.next()启动内层生成器,拿到它产出的第一个值;
  3. 循环中通过yield innerResult.value把内层值传给gen的调用者,同时等待调用者通过next(inputValue)传入新值;
  4. 将收到的inputValue传递给innerIterator.next(),完成向内层生成器的传值,随后进入下一轮循环。

测试示例:

可以通过以下代码验证双向传值逻辑:

(async () => {
  const genIterator = gen();
  // 启动gen,拿到innerGen的初始值0
  console.log((await genIterator.next()).value); // 输出0
  // 传入10,innerGen将i设为10,下一次产出10
  console.log((await genIterator.next(10)).value); // 输出10
  // 传入20,innerGen将i设为20,产出20
  console.log((await genIterator.next(20)).value); // 输出20
})();

内容的提问来源于stack exchange,提问作者xiao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 19:20:49