Search code examples
javascriptnode.jspromisebluebirdneedle.js

Handle successful HTTP promise if one fails in Bluebird


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...

  • I want to call both APIs at the exact same time and process the results when both complete.
  • If the Pricing API fails, I still want to return the Products with no pricing.
  • If the Products API fails, I want to error out and send 500 back to the client.

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?


Solution

  • 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.