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.
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.
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));