I am trying to use Bluebird's Promisify method and it doesn't work

I can't seem to make a simple example work with bluebird. I used the new Promise method and it works, but when I try to use the Promisify method I might be doing something wrong.

exports.makeRequest = function(someText){
    return Promise.resolve(someText);
}

var makeRequestAsync = Promise.promisify(exports.makeRequest);

makeRequestAsync('Testing').then(function(data){
    console.log(data); // --> log never appears
});

      

I really want to understand how promisify works.

+3


source to share


1 answer


Bluebird promisify()

only works with node-line functions that take a callback as their last argument, where this callback takes two arguments, an error and data. Your function does not meet these criteria.

You can read about how it works here .

Also, there is no need to promise a function that already returns a promise. You can simply call this function directly and use its returned promise, since it already promises to return a function.

exports.makeRequest = function(someText){
    return Promise.resolve(someText);
}

exports.makeRequest('Testing').then(function(data){
    console.log(data);
});

      

Working demo: http://jsfiddle.net/jfriend00/n01zyqc6/




Of course, since your function is not actually asynchronous, there seems to be no reason to even use promises with it.


Here's an example where you somehow promise asynchronous and use the correct convention:

exports.myFunc = function(data, callback) {
    // make the result async
    setTimeout(function() {
        // call the callback with the node style calling convention
        callback(0, data);
    }, 500);

};

var myFuncAsync = Promise.promisify(exports.myFunc);

myFuncAsync("Hello").then(function(result) {
    console.log(result);
});

      

+6


source







All Articles