Created
May 4, 2017 15:07
-
-
Save therealshabi/7268b9224c803963ff568ddf0882d8f7 to your computer and use it in GitHub Desktop.
How to make Asynchronous Route in nodejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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