与蓝鸟的承诺异步异常处理 [英] Asynchronous exception handling with bluebird promises
问题描述
这是处理这种情况的最佳方式。我是在受控环境中,我不想崩溃。
What is the best way to handle this scenario. I am in a controlled environment and I don't want to crash.
var Promise = require('bluebird');
function getPromise(){
return new Promise(function(done, reject){
setTimeout(function(){
throw new Error("AJAJAJA");
}, 500);
});
}
var p = getPromise();
p.then(function(){
console.log("Yay");
}).error(function(e){
console.log("Rejected",e);
}).catch(Error, function(e){
console.log("Error",e);
}).catch(function(e){
console.log("Unknown", e);
});
在从setTimeout的内扔,我们总是会得到:
When throwing from within the setTimeout we will always get:
$ node bluebird.js
c:\blp\rplus\bbcode\scratchboard\bluebird.js:6
throw new Error("AJAJAJA");
^
Error: AJAJAJA
at null._onTimeout (c:\blp\rplus\bbcode\scratchboard\bluebird.js:6:23)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
如果发生掷然后setTimeout的蓝鸟捕前将它捡起来:
If the throw occurs before the setTimeout then bluebirds catch will pick it up:
var Promise = require('bluebird');
function getPromise(){
return new Promise(function(done, reject){
throw new Error("Oh no!");
setTimeout(function(){
console.log("hihihihi")
}, 500);
});
}
var p = getPromise();
p.then(function(){
console.log("Yay");
}).error(function(e){
console.log("Rejected",e);
}).catch(Error, function(e){
console.log("Error",e);
}).catch(function(e){
console.log("Unknown", e);
});
结果:
$ node bluebird.js
Error [Error: Oh no!]
这是伟大的 - 但如何将一个手柄这种性质的节点或浏览器的流氓异步回调。
Which is great - but how would one handle a rogue async callback of this nature in node or the browser.
推荐答案
Promises are not domains, they will not catch exceptions from asynchronous callbacks. You just can't do that.
承诺也不过捕捉从内抛出的异常的然后
/ 抓
/ 无极
构造回调。因此,使用
Promises do however catch exceptions that are thrown from within a then
/ catch
/ Promise
constructor callback. So use
function getPromise(){
return new Promise(function(done, reject){
setTimeout(done, 500);
}).then(function() {
console.log("hihihihi");
throw new Error("Oh no!");
});
}
(或只是<一个href=\"https://github.com/petkaantonov/bluebird/blob/master/API.md#promisedelaydynamic-value-int-ms---promise\"相对=nofollow> Promise.delay
),以获得所需的行为。从来没有在定制(非诺)异步回调抛出,始终拒绝周围的承诺。使用的try-catch
,如果它真正需要的。
(or just Promise.delay
) to get the desired behaviour. Never throw in custom (non-promise) async callbacks, always reject the surrounding promise. Use try-catch
if it really needs to be.
这篇关于与蓝鸟的承诺异步异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!