Search code examples
javascriptpromisebluebird

how to wrap a promise with bluebird


I'm using bluebird for promises, but also using a library that returns a non-bluebird promise. I want to use .asCallback. I tried to use Promise.resolve to wrap it, which I found somewhere else online, but it hides the errors in the promise chain. In the code if I take out the then/catch it resolves rather than throwing an error from the client call, even though an error happened.

Besides creating a new promise with new Promise(resolve,reject), which is an obvious solution, is there a better way to convert it to a bluebird promise, one that will propagate any errors to the original promise chain?

module.exports.count = function(params, done){
  var promise = client.count({
    "index": config.search.index + "_" + params.index
  }).then(function(response){
    logger.debug(response);
  }).catch(function(e){
    logger.error(e);
  });
  return Promise.resolve(promise).asCallback(done);

Solution

  • Promise.resolve does propagate errors. Your problem seems to be that catch handles them before they could reach the resolve. You should be doing

    function count(params, done){
      return Promise.resolve(client.count({
        "index": config.search.index + "_" + params.index
      })).then(function(response){
        logger.debug(response);
        return response; // important!
      }, function(e){
        logger.error(e);
        throw e; // important!
      }).asCallback(done);
    }