There are a lot instances where I have to make two database queries that depend on each other .. But because of the asynchronous nature of js, I can't set the order of these query requests. The work around I have been using is put one of the queries in the callback of the other one. My approach seems like its working but I just want to know if there are better ways of doing this?
example code:
app.get('/tweet', function(req,res){
User.findOne({ twitterID: req.user.id },
function(err, user) {
if (user){
var votedPosts = user.votedPosts;
Post.find(function (err, posts) {
if(posts){
for (var i = 0; i < posts.length; i++){
for (var j = 0; j < votedPosts.length; j++){
if(votedPosts[j]._id == posts[i]._id){
posts[i].votetype = votedPosts[j].votetype;
}
else{
console.log("this is getting called");
posts[i].votetype = 0;
}
}
}
res.send(posts);
}
});
}
});
});