最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - I'm trying to use the Bluebird's method Promisify and it's not working - Stack Overflow

programmeradmin1浏览0评论

I'm not able to make a simple example works on bluebird. I've used the new Promise method and it works, but when I try to use the Promisify method I may 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.

I'm not able to make a simple example works on bluebird. I've used the new Promise method and it works, but when I try to use the Promisify method I may 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.

Share Improve this question asked May 8, 2015 at 5:01 Elvio CavalcanteElvio Cavalcante 5165 silver badges10 bronze badges 1
  • 1 You don't need to promisify it. Just call makeRequest, it already returns a resolved promise. – thefourtheye Commented May 8, 2015 at 5:02
Add a ment  | 

1 Answer 1

Reset to default 7

Bluebird's promisify() only works with node-style functions that take a callback as their last argument where that callback takes two arguments, an error and the data. Your function does not meet this criteria.

You can read about how it works here.

In addition, there's no need to promisify a function that already returns a promise. You can just call that function directly and use its returned promise since it's already a promise returning function.

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

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

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


Of course, since your function isn't actually async, there doesn't appear to be any reason to even use promises with it at all.


Here's an example of actually promisifying something that is async and uses the right calling 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);
});
发布评论

评论列表(0)

  1. 暂无评论