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.

1
  • find looks like it is async, so you are returning before it is finished Commented Nov 14, 2016 at 22:10

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

4 Comments

it's just return me [ Promise { <pending> }, Promise { <pending> } ]
That's correct, it should return a promise.. your nearly there.. Basically you need to attach a then.. eg. findUser('xyz').then(function (data) {
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 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.