I'm fairly new to Promises and have been attempting to get this piece of code to work properly. Here's what I have.
var Promise = require('bluebird');
Promise.join(getProducts, getPricing, function(products, pricing) {
console.log('products: ' + products.body);
console.log('pricing: ' + pricing.body);
// Add pricing to products here
res.send(products.body);
})
.catch(function(e) {
console.log(e);
res.sendStatus(500);
});
Requirements...
My code seems to work if both API calls are successful, but will always go into the catch if either fail and ignore any successful calls.
I can get this working fine if I use a synchronous Promise chain, but I'd like to call both APIs at the same time.
How can I call both APIs asynchronously and process the results outside of the catch?
You'll want to put a catch
on exactly the promise whose failure you want to handle - i.e. getPricing
.
Promise.join(getProducts, getPricing.catch(function(err) {
// ignore or log?
return null;
}, function(products, pricing) {
console.log('products: ' + products.body);
if (pricing) {
console.log('pricing: ' + pricing.body);
// Add pricing to products here
} // else?
res.send(products.body);
}).catch(function(e) {
console.log(e);
res.sendStatus(500);
});
You can also use getPricing.reflect()
if you want to more explicitly distinguish the two cases.