使用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
相关产品推荐
相关产品推荐

