处理成功的HTTP承诺,如果一个蓝鸟失败

我对Promises相当陌生,一直试图让这段代码正常工作。 这是我的。

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); }); 

要求…

  • 我想同时调用这两个API,并在两个完成时处理结果。
  • 如果定价API失败,我仍然希望返回没有定价的产品。
  • 如果产品API失败,我想错误发送500回到客户端。

我的代码似乎工作,如果两个API调用都成功,但总是进入捕获,如果失败,并忽略任何成功的调用。

如果我使用同步Promise链,我可以很好地工作,但是我想同时调用这两个API。

我怎样才能asynchronous调用这两个API并在catch之外处理结果?

你会想要catch你想要处理的承诺 – 即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); }); 

如果您想更明确地区分两种情况,也可以使用getPricing .reflect()

预警:我有承诺的体面,但不是这个特定的图书馆。

 var Promise = require('bluebird'); var pricing = getPricing().catch(function(e) { return null; }) Promise.join(getProducts, pricing, function(products, pricing) { console.log('products: ' + products.body); console.log('pricing: ' + pricing ? pricing.body : '<null>'); // Add pricing to products here res.send(products.body); }).catch(function(e) { console.log(e); res.sendStatus(500); }); 

修改getPricing(),使它永远不会失败。 最简单的方法是添加一个顶级的.catch() 。 下面的示例代码包装了getPricing()方法

 var Promise = require('bluebird'); function getProducts(){/* add implementation */}; function originalGetPricing(){/* add implementation */}; function getPricing(){ return originalGetPricing() .catch(function(err) { return Promise.resolve(/* replace this comment with empty object or some other suitable response */); }); }; 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); });