Is there a way to run the code sequentially in node.js, I am trying to run the below code and it i snot working as expected
for(var i =0; i < userList.length; i++) {
console.log("============userList========="+userList[i]);
Db.findOne({"_id" : Number(userList[i])}, { "flag" : 1 }, function(err, result) {
if(result && (result.get("flag.notify") === true)) {
console.log("========my condition========="+result);
}
});
}
console.log("===reached here===");
callback(null, MyResult);
I want the above code to iterate and check the condition in the db, but this is not happening here. Any clues ?
There is a very good node.js library "async" for managing the control flow in a asynchronous environment. For this specific issuse https://github.com/caolan/async#forEach series version helps you to solve this issue
async.forEachSeries(userList,function(user,cb){
console.log("============userList========="+user);
Db.findOne({"_id" : Number(user)}, { "flag" : 1 }, function(err, result) {
if(result && (result.get("flag.notify") === true)) {
console.log("========my condition========="+result);
}
cb();
});
},function(err){
console.log("===reached here===");
callback(null, MyResult);
})
there might be some syntax issue but it shows you some direction about solving your issue.