我正在尝试使用 Bluebird 的方法 Promisify,但它不起作用

I'm trying to use the Bluebird's method Promisify and it's not working

我无法在 bluebird 上创建一个简单的示例。我使用了 new Promise 方法并且它有效,但是当我尝试使用 Promisify 方法时,我可能做错了。

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
});

我真的很想了解 promisify 是如何工作的。

Bluebird 的 promisify() 仅适用于将回调作为其最后一个参数的节点样式函数,其中该回调采用两个参数,一个错误和数据。您的函数不符合此条件。

您可以阅读它的工作原理 here

此外,无需对已经 returns 承诺的函数进行承诺。您可以直接调用该函数并使用其返回的承诺,因为它已经是一个承诺返回函数。

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

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

工作演示:http://jsfiddle.net/jfriend00/n01zyqc6/


当然,由于您的函数实际上并不是异步的,因此似乎根本没有任何理由对它使用 promises。


这是一个实际承诺异步并使用正确调用约定的示例:

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);
});