0
module.exports.findUser = function(query){
  var result = []; 
  User.find(query, function(err, data){
    result.push(data);
  });
  return result;
}

I try to push the data array into result, but keep getting an empty array back.

Uriel
  • 15,579
  • 6
  • 25
  • 46

1 Answers1

3

User.find() is async, so you can't just return the value immediately. You have two options to solve this problem:

Option 1:

Accept a callback parameter and call it when results are ready:

module.exports.findUser = function(query, cb) {
    var result = []; 
    User.find(query, function(err, data){
        result.push(data);
        cb(err, result);
    });
}

Common Node.js convention is to have callbacks that have the first parameter err, which would return any errors, and the second parameter the actual data you're giving back.

This would then be used like:

findUser('query', function (err, data) {
    if (err) throw new Error(err);
    console.log(data);
});

Option 2:

Return a Promise which can then be chained. This isn't super common Node.js convention (Option 1 is), but it's becoming a more prevalent and will likely become the norm in a year or two:

module.exports.findUser = function(query) {
    return new Promise(function(resolve, reject) {
        var result = []; 
        User.find(query, function(err, data){
            err && reject(err) || result.push(data) && resolve(result);
        });
    }
}

This would be used like this:

findUser('query').then(result => console.log(result)).catch(err => throw new Error(err));
samanime
  • 25,408
  • 15
  • 90
  • 139
  • it's just return me [ Promise { }, Promise { } ] – user3218020 Nov 14 '16 at 22:58
  • That's correct, it should return a promise.. your nearly there.. Basically you need to attach a `then`.. eg. `findUser('xyz').then(function (data) {` – Keith Nov 14 '16 at 23:00
  • `This isn't super common Node.js convention` Finger crossed this will change, I've heard that Node developers are even on about making built-in's Promise based.. That with the `async` & `await` will be great.. – Keith Nov 14 '16 at 23:02
  • @Keith I've noticed them trending more and more with Promises too, which makes me happy. I'm a big fan of promises. An interesting thing is you can actually do BOTH as well, accept a callback and return a Promise. They aren't mutually exclusive. – samanime Nov 15 '16 at 15:00