我很難理解JavaScript承諾。我正在尋找滿足一定條件的對象的Mongoose模型,如果它們存在,我想將該對象變成一個普通的JS對象並添加一個屬性到它。異步findOne()操作forEach循環內
不幸的是,我無法將我的頭圍繞在如何確保我的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);
});
}
我已經看過類似的問題,但無法得到答案。感謝幫助。
避免['Promise'構造反模式](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-它),並且不要使用'forEach'!你正在尋找'Promise.all' – Bergi
好吧,由於異步代碼是異步的,你可以在異步結果可用之前清楚地解決'challengesArray' –