1 回答

TA贡献1865条经验 获得超7个赞
我相信您的代码中的问题出在user.products.map(...)函数上,因为您永远不会等待您在地图中创建的所有承诺都得到解决。
换句话说,该map函数返回一个待处理的 Promise 数组,但它不会等待它们完成,因此执行会继续执行,直到到达res.status(...)任何代码map执行之前的其余代码。
你有不同的选择来解决它,但主要是你需要处理map函数返回的承诺数组并等待它们完成,然后再结束你的代码。async/await在Google Developers Web 基础指南中有一个很好的解释如何处理这种情况。
我通常利用Promise.all()函数,它从承诺数组中返回一个承诺,因此您可以等到代码中的代码为数组中的每个项目并行map执行(即在您的情况下)。您可以在MDN 文档中阅读更多相关信息。product
// ...
let promisesArray = user.products.map(async product => {...});
// promisesArray should look like: [Promise { <pending> }, Promise { <pending> }, … ]
// Using Promise.all we wait for each of them to be done in parallel
await Promise.all(promisesArray);
// Now you are certain the code in the map has been executed for each product
// ...
一个好的做法是使用try {} catch(err) {}块Promise.all()来处理某些承诺被拒绝的情况
添加回答
举报