I've become aware of Promise anti-patterns and fear I may have fallen for one here (see code extract from within a function). As can be seen, I have Promises nested within two node asynchronous functions. The only way I have been able to expose the inner Promise is by using an outer one. I'd welcome guidance on how to write this 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 also caught the issue in this plnkr
fs.readFile(), then you can simply return thePromise.all()result from thefs.readFileAsync().then()handler and you will not need the outer promise that you are manually creating. that scheme also tends to handle errors better too. All your async actions will be chained into one promise that you return. That's how you avoid creating new promises.return Resto.find(...).then(...)could already work.