I am trying to send the response when the loop k value is equal to users[0].employees.length, but it's directly moving forward to max length, how do I solve it
Userlist.find(queryObj).exec(function (err, users) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
else {
console.log('found users list', users);
// res.json(users[0].employees);
var k=0;
var resparr=[]
for(var i=0;i<users[0].employees.length;i++){
k++;
User.find({"_id":users[0].employees[i]._id}).exec(function(err,user){
resparr=resparr.concat(user);
console.log("resparray:",k,resparr.length,i,users[0].employees.length)
if(k==users[0].employees.length)
{
console.log("success",resparr)
res.json(resparr);
}
})
}
}
});
You are using an asynchronous function call within a synchronous loop. The loop will always finish before your callback functions are called.
You will need some kind of asynchronous looping. For a native solution you can use Promises:
For utility packages in node.js, I'd recommend the package
asyncfor a callback based solution orbluebirdfor Promises. Both have a.mapfunction which is perfect for this use case.