Just started working with Nodejs and facing this issue while pushing the array as a response in the below code. I know this is happening because of the asynchronous nature of Nodejs, tried to apply async as well but did not get the desired result. Could someone let me know the fix of this code:
array = [];
var company = companySchema.Company;
company.findOne({_id: companySchema.objectId(req.tempStore.companyId)}, function (err, comp) {
if (err) {
console.log(err);
}
else {
var i;
var length = comp.events.length;
var dataset = datasetSchema.dataset;
for (i = 0; i < length; i++) {
dataset.find({companyId:comp.events[i]}, function (err,data) {
if (err) {
console.log(err);
}
else {
array.push(data);
}
console.log("array-----"+array); // prints array here
});
}
}
console.log("array-----"+array); // array is empty hence causing empty response
res.response.data = array;
next();
});