【发布时间】:2019-09-03 04:09:44
【问题描述】:
我们正在使用 async 和 await 从另一个函数收集计数,但遇到 Promise 问题,我们知道使用 then() 但需要更新外部数组/对象。
我们怎么能等着更新forEach元素并推送到数组?
示例代码:
module.exports = {
getQuestionCounts: function(req, res){ // connected with Routes
var arr = [];
req.data.forEach(element => {
module.exports.getCounts(element).then(function(count){
console.log(count); // getting value
element.count = count;
arr.push(element); // not updating with array
});
});
if(arr.length > 0){ // other operations }
}
getCounts: async function(data){
var count = await Questions.countDocuments({"object":{$elemMatch: {data}}}).then(function(result){
return result;
});
console.log(count); // getting count Fine
return count;
}
}
【问题讨论】:
-
Got soultion : 使用this找到对解决我的问题很有帮助