【发布时间】:2017-11-03 08:37:19
【问题描述】:
我很难理解 JavaScript Promises。我正在我的 Mongoose 模型中搜索满足特定条件的对象,如果它们存在,我想将该对象变成一个普通的 JS 对象并在其上添加一个属性。
不幸的是,我无法弄清楚如何确保我的forEach 循环在我的承诺最终解决之前完全运行。请看我的代码。
// Called to check whether a user has participated in a given list of challenges
participationSchema.statics.getParticipation = function(user, challenges) {
return new Promise((resolve, reject) => {
challengesArray = [];
challenges.forEach((challenge) => {
// Model#findOne() is Async--how to ensure all these complete before promise is resolved?
Participation.findOne({user, challenge})
.then((res) => {
if (res) {
var leanObj = challenge.toObject();
leanObj.participation = true;
challengesArray.push(leanObj);
}
})
.catch(e => reject(e));
})
console.log("CHALLENGES ARRAY", challengesArray); // Challenges Array empty :(
resolve(challengesArray);
});
}
我查看了类似的问题,但无法得到答案。感谢您的帮助。
【问题讨论】:
-
避免使用
Promiseconstructor antipattern,不要使用forEach!您正在寻找Promise.all -
好吧,因为异步代码是异步的,你显然在异步结果可用之前解析
challengesArray
标签: javascript node.js asynchronous mongoose promise