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

如何在循环中等待所有Promise执行完成后再返回结果?

问题原因与解决方案

报错原因

你遇到的SyntaxError: await is only valid in async function报错,是因为await关键字只能在被async关键字修饰的函数内部使用,Node 14支持的顶级await仅适用于ES模块顶层作用域,普通函数/CommonJS模块下都需要为外层函数添加async声明。
另外你最初的写法没有等待所有异步查询完成就直接返回types,所以count属性没有完成赋值。

方案1:串行执行(原有写法修复)

给你当前代码所在的外层函数添加async修饰即可正常运行,代码示例:

// 注意外层函数必须加async关键字
async function getDeviceTypeCounts() {
  const types = config.deviceTypes
  for (const type of types) {
    const results = await db.find({
      selector: {
        type: { $eq: type.name }
      }
    })
    type.count = results.docs.length
  }
  return types
}
// 调用该函数时需要用await或者.then拿结果
// 示例调用:const typeCounts = await getDeviceTypeCounts()

优化提示:如果你只需要统计匹配条目数量,不需要获取完整文档内容,可以给db.find添加fields: ['_id']参数,减少返回数据体积,提升查询效率。

方案2:并行执行(性能更优)

如果deviceTypes的条目较多,串行依次查询效率较低,可以用Promise.all同时发起所有查询请求,缩短整体执行时间:

async function getDeviceTypeCounts() {
  const types = config.deviceTypes
  // 批量生成所有查询的Promise
  const countQueries = types.map(async type => {
    const results = await db.find({
      selector: {
        type: { $eq: type.name }
      }
    })
    type.count = results.docs.length
    return type
  })
  // 等待所有查询完成
  return Promise.all(countQueries)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:27:00