我正在尝试使用一个不实现 Node 约定的库,即如果不存在错误,则将错误值作为错误值传递,该约定用于 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 }}
有什么想法吗?
最佳答案
使用两个参数调用原始回调:status
和 reply
。
你的promisifier正在用resolve
替换该回调,因此也会用两个参数调用,并且由于它只需要一个,所以第二个参数会丢失(因此未定义
)。
试试这个:
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()
,它将接收数组作为第一个参数。
关于javascript - 无法获得与 Bluebird promisfy 一起使用的非 Node 回调库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34710676/