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

Elv*_*nte 3 javascript asynchronous promise bluebird

我无法在蓝鸟上做一个简单的例子.我已经使用了新的 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
});
Run Code Online (Sandbox Code Playgroud)

我真的很想了解promisify是如何运作的.

jfr*_*d00 6

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

你可以在这里阅读它的工作原理.

此外,没有必要宣传已经返回承诺的函数.您可以直接调用该函数并使用其返回的promise,因为它已经是promise返回函数.

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

exports.makeRequest('Testing').then(function(data){
    console.log(data);
});
Run Code Online (Sandbox Code Playgroud)

工作演示: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);
});
Run Code Online (Sandbox Code Playgroud)