javascript - Avoiding Promise anti-patterns with node asynchronous functions -


i've become aware of promise anti-patterns , fear may have fallen 1 here (see code extract within function). can seen, have promises nested within 2 node asynchronous functions. way have been able expose inner promise using outer one. i'd welcome guidance on how write more elegantly.

function xyz() {     return new promise(function(resolve, reject) {         return resto.find({recommendation: {$gte: 0}}, function (err, data) {             if (err) return reject("makesitemap: error reading database");              return fs.readfile(__dirname + '/../../views/sitemap.jade', function(err, file) {                 if (err) return reject("makesitemap: error reading sitemap template");                  [snip]                  resolve(promise.all([                     nlpromise('../m/sitemap.xml', map1),                     nlpromise('../m/sitemap2.xml', map2)                 ]));             });         });     }); } 

i've caught issue in plnkr

the best solution create promise versions of callback-using functions. bluebird, excellent promise implementation (better node’s native one), has built-in.

bluebird.promisifyall(resto); // if can promisify prototype, that’s better bluebird.promisifyall(fs);  function xyz() {     return resto.findasync({recommendation: {$gte: 0}}).then(function (data) {         return fs.readfileasync(__dirname + '/../../views/sitemap.jade').then(function (file) {             …              return bluebird.all([                 nlpromise('../m/sitemap.xml', map1),                 nlpromise('../m/sitemap2.xml', map2)             ]);         });     }); } 

also, if fs.readfile doesn’t depend on resto.findasync, should run them together:

return bluebird.all([     resto.findasync({recommendation: {$gte: 0}}),     fs.readfileasync(__dirname + '/../../views/sitemap.jade'), ]).spread(function (data, file) {     …      return bluebird.all([         nlpromise('../m/sitemap.xml', map1),         nlpromise('../m/sitemap2.xml', map2),     ]); }); 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -