蓝鸟承诺和回调,没有错误参数 [英] Bluebird promisify and callback with no error argument

查看:50
本文介绍了蓝鸟承诺和回调,没有错误参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图使一个不使用callback(err, data)模式的第三方库.相反,它们总是在错误时返回callback(data)throw.

I'm trying to promisify a 3rd party library that doesn't use the callback(err, data) pattern. Instead they always return callback(data) and throw on errors.

Promise.promisifyAll(horse);

var p = Promise.defer();
horse.drinkAsync()
    .error(function(data)
    {
        p.fulfill(data);
    })
    .catch(function (err)
    {
        console.error('error occured', err);
    });

return p.promise;

有什么好的方法可以用诺言包装这样的行为,并且仍然让它看起来正常并允许捕获抛出的错误? catch子句不触发,应用程序崩溃.

What is a nice way to wrap such a behavior with promises and still have it look ok and allow to catch the thrown error? The catch clause doesn't trigger and the application crashes.

推荐答案

从Bluebird 2.1开始,您现在可以使用自定义的Promisification处理程序来自定义promisifyAll:

From Bluebird 2.1 on, you can now customize promisifyAll with a custom promisification handler:

function noErrPromisifier(originalMethod){
    return function promisified() {
         var args = [].slice.call(arguments); // might want to use smarter
         var self = this                      // promisification if performance critical
         return new Promise(function(resolve,reject){
             args.push(resolve); 
             originalMethod.apply(self,args); // call with arguments
         });
    };
}

var horse = Promise.promisifyAll(require("horse"), {
    promisifier: noErrPromisifier
});

horse.drinkAsync().then(function(data){
     // Can use here, ow promisified normally.
});

如果原始方法是异步抛出的,则实际上没有办法将其包装在域中,尽管我从未见过一个库表现不佳.

If the original method throws asynchronously, there is really no way around wrapping it in a domain, although I've never seen a library that acts that poorly.

这篇关于蓝鸟承诺和回调,没有错误参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆