无法获得非节点回调库以与 Bluebird promisfy 一起使用

Can't get a non-node callback library to work with Bluebird promisfy

我正在尝试使用一个库,它没有实现节点约定,即如果不存在错误,则将错误值作为错误值传递,用于 Bluebird 的 promisifyAll 函数。

API 的实现可以在这里找到:https://github.com/sintaxi/dbox/blob/master/lib/dbox.js

我已经实现了一个自定义函数来解决这个问题,但是在使用它时我无法将第二个值打印到控制台。

function NoErrorPromisifier(originalMethod) {
    // return a function
    return function promisified() {
        var args = [].slice.call(arguments);
        // Needed so that the original method can be called with the correct receiver
        var self = this;
        // which returns a promise
        return new Promise(function(resolve, reject) {
            args.push(resolve, reject);
            originalMethod.apply(self, args);
        });
    };
}

var client = Promise.promisifyAll(app.client(token), {
  promisifier: NoErrorPromisifier
});

client.accountAsync().then(function(status, reply){
  console.log(status, reply)
}).catch(function(err){
  console.log(err)
})

这输出:200 undefined

然而,使用传统的回调方式:

client.account(function(status, reply){
  console.log(status, reply)
})

这输出:200 {{ json }}

有什么想法吗?

Promises/A+ 标准将 resolve 和“onFulfilled”函数定义为接受单个参数,即解析值。同样,onFulfilled 单个 return 值 进一步传播到以下 onFulfilled 函数(通过 then 附加)。

client.accountAsync().then(function(status, reply){

尝试接收两个增强,但这是不可能的,因此在记录时 reply undefined 被记录。

使用两个参数调用原始回调:statusreply

你的 promifier 正在用 resolve 替换那个回调,因此 被调用时有两个参数,因为它只需要一个,所以第二个参数丢失了(因此 undefined)。

试试这个:

args.push(function() { resolve([].slice.call(arguments)) });

这将导致使用包含调用回调的参数的数组调用 resolve,为此 Bluebird 具有(可选).spread() 方法:

client.accountAsync().spread(function(status, reply){
  console.log(status, reply)
}).catch(function(err){
  console.log(err)
})

如果您使用 .then(),它将接收数组作为第一个参数。