Mad*_*d0g 9 node.js promise bluebird
我正在尝试宣传不使用该callback(err, data)模式的第三方库.相反,他们总是返回callback(data)和throw上的错误.
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;
Run Code Online (Sandbox Code Playgroud)
用promises包装这样一个行为的好方法是什么,它仍然看起来没问题,并允许捕获抛出的错误?catch子句不会触发,应用程序崩溃.
从Bluebird 2.1开始,您现在可以promisifyAll使用自定义的promisification处理程序进行自定义:
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.
});
Run Code Online (Sandbox Code Playgroud)
如果原来的方法异步抛出,实在绕在一个域中包裹它没有办法,虽然我从来没有见过作用图书馆是知之甚少.
| 归档时间: |
|
| 查看次数: |
1596 次 |
| 最近记录: |