Unfortunately you can't. When you execute a function, you get whatever you return from it. If you return nothing you get undefined
by default.
Instead of having your readability based on getting the user
, you should have it based on what you're going to do with it once you've gotten it. Presumably you'll have some action(s) that you'll want to perform on the user, right? This is where Promises can make your code look significantly better than callbacks.
Here's that code re-written with Promise
getAll: function(callback){
return User.findAsync({});
}
api.getAll()
.then(console.log)
.catch(console.error);
Since all you wanted to do was "perform" console.log
on your users
(and/or console.error
on err
in case that happens) that's exactly what the above code does.
Note that I used findAsync
, which came from Bluebird's promisification
But more realistically you'd have functions that do other things to/with your user
api.getAll()
.then(filterSome)
.then(manipulateSome)
.then(sendSomewhere)
.catch(console.error);
Each of those functions might look something like this:
function filterSome(users){
return users.reduce(function(p,e){
if(…) p.push(e);
return p;
},[]); }
They can even be async functions in which case you'll have to use more Promises:
function manipulateSome(users){
return new Promise.all(user.map(function(user){
return new Promise(function(resolve){
someAsyncFunction(user, function(err, result){
user.someProp = result.manipulated;
resolve(user);
}); }); }));}
If that still looks messy, then know that with upcoming ES7 all the above would get a syntactic sugar and you would do something like this:
getAll: async function(callback){
return User.findAsync({});
}
try{
var users = await api.getAll();
console.log(users);
catch(e){
console.error(e)
}
You could start using it today with transpilers like BabelJS