0

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

Dhyey
  • 4,275
  • 3
  • 26
  • 33
jine
  • 99
  • 2
  • 7

1 Answers1

1

You need to wrap it in a promise like this:

app.get('/getusers', function(req, res) {
    getAllUsers()
    .then(tmpUsrList => {
        console.log(tmpUsrList);
        res.send(tmpUsrList);
    })
    .catch(err => handleError(err))
});

function getAllUsers() {
    return new Promise((resolve, reject) => {
      userModel.find({}, function(err, userlist) {
          if (err) return reject(err);
          // no need of else if you return
          console.log(userlist);
          resolve(userlist);
      });
    })
}
Dhyey
  • 4,275
  • 3
  • 26
  • 33