I'm writing a function that return a list with all the users registered in the Mongo database.
function getUsers() {
db.collection('users').find({}, {username: true}, function(error, results) {
if (results) return results;
return [];
});
}
The problem is that Mongoose needs an anonymous function to get the results, and if I try to return those results when I have it, return only affects to the anonymous function, so parent function returns undefined. I suppose Mongoose runs the anonymous function asynchronously.
What is the best way to solve this?
Thanks.
You are right; returning from an asynchronous function doesn't have any meaning. You need to handle the results of your database operation asynchronously. (You could use promises, as Kamugo mentions, but even promises use a callback function).
The most straight-forward way to make this work is to make getUsers
asynchronous by passing in a callback, and using that callback for the callback to find
:
function getUsers(callback) {
db.collection('users').find({}, {username: true}, callback);
}
And then use it like this:
getUsers(function(error, results) {
if (results) {
// do something with results
} else {
// no results
}
});