node.js - How to get data back from Mongoose without using a callback? -
ultimately knowledge bad started few hours ago. in head should work:
getall: function(callback){ user.find({}, function (err, data) { if (err) return console.error(err); return data; }); } var users = api.getall(); console.log(users); //undefined
but reason have pass callback data working so:
getall: function(callback){ user.find({}, function (err, kittens) { if (err) return console.error(err); callback(kittens); }); } var users = api.getall(function (data) { console.info(data); //does output data });
how can option one, easier read of 2 work?
unfortunately can't. when execute function, whatever return it. if return nothing undefined
default.
instead of having readability based on getting user
, should have based on you're going once you've gotten it. presumably you'll have action(s) you'll want perform on user, right? promises can make code better callbacks.
here's code re-written promise
getall: function(callback){ return user.findasync({}); } api.getall() .then(console.log) .catch(console.error);
since wanted "perform" console.log
on users
(and/or console.error
on err
in case happens) that's above code does.
note used findasync
, came bluebird's promisification
but more realistically you'd have functions other things to/with user
api.getall() .then(filtersome) .then(manipulatesome) .then(sendsomewhere) .catch(console.error);
each of functions might this:
function filtersome(users){ return users.reduce(function(p,e){ if(…) p.push(e); return p; },[]); }
they can async functions in case you'll have 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 still looks messy, know upcoming es7 above syntactic sugar , this:
getall: async function(callback){ return user.findasync({}); } try{ var users = await api.getall(); console.log(users); catch(e){ console.error(e) }
you start using today transpilers babeljs
Comments
Post a Comment