2

I have a really simple API, that grabs some data from a server, does a little processing and then sends it to the client. I'm trying to 'Promisify' this little module. Heres an example

var MyModule = function (){}

MyModule.prototype.makeRequest = function(requestURL){

    //Set request up
    //Return the promise for the request.
    return request(requestOptions);
}

MyModule.prototype.myFunction = function(var1, var2, cb){

    var URL = "http://....//";

    this.makeRequest(URL)
        .then(function(data)
        {
            //Some processing logic
            cb(null,data);
        })
        .catch(function(err)
        {
            cb(err,null);
        })
}

module.exports = MyModule;

Then to consume this module I want to do the following...

 var MyModule = new(require('../lib/MyModule'));

 MyModule.myFunction(var1,var2)
            .then(function(data)
            {
                console.log(data);
            }).catch(function(err){
                console.log(err);
            });

How can I get this to work using BlueBird? I've been experimenting with PromisifyAll() like so..

var MyModule = new(require('../lib/MyModule'));
var Promise = require("bluebird");
var MyModuleAsync = Promise.promisifyAll(MyModule);

My approach to this is obviously incorrect and I'm aware that I can create and return the promise manually inside the API but the docs suggest I shouldn't need to do this.

LiamB
  • 18,243
  • 19
  • 75
  • 116
  • 1
    Um, it looks like `MyModule.prototype.myFunction` already uses promises internally. You should really, really fix that library and make it return them instead of taking a callback. – Bergi Jul 20 '15 at 17:27
  • @bergi - it uses a library (request-promise) that returns a promise, but I need to do a little extra processing before passing the data back. All the docs i've seen said you should really return a promise and just use Bluebird's promisify feature? – LiamB Jul 20 '15 at 19:39
  • 1
    If you have to do extra processing, do it in a promise `then` callback and return the resulting promise. Don't fall back to regular callbacks. That's basically the [promise construction antipattern](http://stackoverflow.com/q/23803743/1048572) stretched out between two modules and obscured by using `promisify`. – Bergi Jul 20 '15 at 19:43
  • I see - great link! OK cool, will have a look at converting that. Thank-You – LiamB Jul 20 '15 at 19:46

1 Answers1

1

Start off by promisifying a single function

var MyModule = new(require('../lib/MyModule'));
var Promise = require("bluebird");
var MyModuleAsync = Promise.promisify(MyModule.myFunction, MyModule);

MyModuleAsync(var1, var2).then(function(res){
  // etc
});

Once you get that working, you can start thinking about imlementing promisifyAll()

Yuri Zarubin
  • 11,439
  • 4
  • 30
  • 33