node.js - NodeJS - Q - How to pass a promise in another promise -
i want return or pass promise promise don't know how that. codes:
function seedusers(){ var def = q.defer(); _seedusersindb(function(err, users){ if(err){ return def.reject(err); } def.resolve(users); }) return def.promise; } function seeddb(){ var def = q.defer(); _checkcountofusers(function(count){ if(count > 0){ // seeded return def.resolve(); } else{ // have use seedusers() // ???????????????????? // how pass seedusers() ???? // ???????????????????? } }) return def.promise; }
what codes put in specified section? thanks
mixing promisified , unpromisified functions messy, therefore promisify both low level functions :
// promisify _seedusersindb() function _seedusersindbasync() { var def = q.defer(); _seedusersindb(function(err, users) { if(err) def.reject(err); else def.resolve(users); }); return def.promise; } // promisify _checkcountofusers() function _checkcountofusersasync() { var def = q.defer(); _checkcountofusers(function(err, count) { if(err) def.reject(err); else def.resolve(count); }); return def.promise; }
now, nodebacks disappear higher level code, in favour of promise chains.
function seeddb() { return _checkcountofusersasync.then((count) => { return (count > 0) ? count : _seedusersindbasync().then((users) => users.length); }); }
Comments
Post a Comment