0

I've got a function which queries my Mongo database, and should be returning some values.

foo: function(req, res) {
    var users = getAllTokens();
    console.log(users);
}

function getAllTokens() {
    Token.find().populate('user').exec(function(err,rec) {
        console.log(rec);
        return rec;
    });
}

So the line console.log(users) returns undefined, however the console.log(rec) line returns the correct values.

Maybe its just too early for me, but this should be really simple, I'm just not seeing the problem.

If it helps, my Mongo database is stored remotely so there is a delay in getting the results (but the exec function is a callback..)

Unsure of how this is a duplicate. If I switch to promises, I still get the same outcome:

function getAllTokens() {
    Token.find().populate('user')
    .then(function(rec){
        console.log(rec);
        return rec;
    })
    .catch(function(err){
        console.log(err);
    })
}

return rec is undefined, yet the logged rec is populated

K20GH
  • 6,032
  • 20
  • 78
  • 118
  • Im not sure how this is a duplicate. Waterline uses callbacks, so it should not be returning before the function has been called – K20GH Jan 21 '17 at 10:11
  • You misunderstood asynchronism. Please read the duplicate question's accepted answer quietly – Yann Bertrand Jan 21 '17 at 11:06

0 Answers0