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

使用Mongoose查询地区国家列表时Promise.all实现错误无输出如何解决

核心错误点

  • forEach 方法不支持等待 async 回调执行完成,所有数据库查询的异步操作还没执行完毕时,代码就已经走到了 Promise.all 这一步,此时存储结果的 regCountryList 还是空数组。
  • Promise.all 要求传入的参数是 promise 数组,你当前往 regCountryList 中插入的是异步查询完成后才会生成的普通对象,而非 promise,Promise.all 无法起到等待所有异步任务完成的作用。

修正方案

将 forEach 替换为 map,把每个区域的查询操作包装为 promise 存入数组,再通过 Promise.all 等待所有 promise 执行完成后再返回结果,同时补充异常捕获逻辑避免请求无响应。

修正后代码

router.get("/FRPListing", async (req, res) => {
  try {
    const countryList = ["Europe and UK", "Africa", "Middle East and Gulf", "Eurasia", "Asia", "Australasia", "North America", "Central America Caribbean", "South America", "Global"];
    // 生成所有区域查询的promise数组
    const queryPromises = countryList.map(async (region) => {
      const countries = await FRPObj.find({ Region: region }, 'Region Country')
        .sort({ Country: 1 })
        .distinct('Country')
        .exec();
      return {
        Region: region,
        Countries: countries
      };
    });
    // 等待所有查询完成拿到最终结果
    const regCountryList = await Promise.all(queryPromises);
    res.send({ status: 200, results: regCountryList });
  } catch (error) {
    res.status(500).send({ status: 500, message: "查询失败", error: error.message });
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:39:01