I am developing a simple angular2/ expressJS application. I have an http get router call in expressJS as follow, which should return all users from mongoDB and this works fine:
app.get('/getusers', function(req, res) {
userModel.find({}, function(err, userlist) {
if (err) return handleError(err);
else {
return userlist;
}
});
Now I am trying to split the get user list part into a separate function as below, so that it can be reused.
app.get('/getusers', function(req, res) {
var tmpUsrList = getAllUsers();
console.log(tmpUsrList); //This prints undefined
res.send(tmpUsrList);
});
function getAllUsers() {
userModel.find({}, function(err, userlist) {
if (err) return handleError(err);
else {
console.log(userlist); //This prints the correct list
return userlist;
}
});
}
However, after the return, the value is becoming undefined. I am from a java background, so I may be doing some basic mistake. Appreciate your help!!
Thanks