Skip to content

Instantly share code, notes, and snippets.

@therealshabi
Created May 4, 2017 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save therealshabi/7268b9224c803963ff568ddf0882d8f7 to your computer and use it in GitHub Desktop.
Save therealshabi/7268b9224c803963ff568ddf0882d8f7 to your computer and use it in GitHub Desktop.
How to make Asynchronous Route in nodejs
var calls = [];
// HomeStreamPost Part-2
// route to get the homeStream post of a particular user
server.get("/user/homeStreamPost/:email_address",function(req,res,next){
var result=[];
req.assert('email_address','Email Address is required').notEmpty().isEmail();
var errors = req.validationErrors();
if (errors) {
helpers.failure(res,next,errors[0],400);
}
UserModel.findOne({email_address: req.params.email_address }, function (err, user) {
if(err) {
helpers.failure(res,next,'Something went wrong while fetching user from the database',500);
}
if(user === null) {
helpers.failure(res,next,'This user does not exist',404);
}
var f_posts = user.following_post;
var pushDoc = function(item, callback) {
if(item) {
PostModel.findOne({ _id: item}, function(err, post) {
if(post != null) {
result.push(post);
//Return to function which called this function
callback();
}
else callback();
});
}
};
//This function will call callback for each user following list to pushDoc function
async_query.forEach(f_posts, pushDoc , function(err) {
//err will be generated when finished traversing the error
if(err)
console.log(err);
helpers.success(res,next,result);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment