We are using async
and await
to collect the count from another function but getting Promise Issues, We know to use then()
but need to update outer array/object.
How can we wait still update forEach
element and push to the array?
sample code :
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;
}
}