有没有可能在Promise中出现错误?
请看下面的代码作为参考,我想让promise1.catch捕获promise2中生成的错误(当前代码不适用于此代码):
function test() {
var promise1 = new Promise(function(resolve1) {
var promise2 = new Promise(function(resolve2) {
throw new Error('Error in promise2!');
});
promise2.catch(function(error2) {
console.log('Caught at error2', error2);
});
});
promise1.catch(function(error1) {
console.log('Caught at error1', error1);
});
}
test();发布于 2014-07-30 19:18:12
是的!!
promises中的错误传播是它最强大的优势之一。它的行为与同步代码中的行为完全相同。
try {
throw new Error("Hello");
} catch (e){
console.log('Caught here, when you catch an error it is handled');
}非常类似于:
Promise.try(function(){
throw new Error("Hello");
}).catch(function(e){
console.log('Caught here, when you catch an error it is handled');
});就像在顺序代码中一样,如果您想对错误执行一些逻辑,但不想将其标记为已处理-您可以重新抛出它:
try {
throw new Error("Hello");
} catch (e){
console.log('Caught here, when you catch an error it is handled');
throw e; // mark the code as in exceptional state
}它变成了:
var p = Promise.try(function(){
throw new Error("Hello");
}).catch(function(e){
console.log('Caught here, when you catch an error it is handled');
throw e; // mark the promise as still rejected, after handling it.
});
p.catch(function(e){
// handle the exception
});请注意,在Bluebird中,您可以使用类型捕获和条件捕获,因此,如果您所做的只是对promise的类型或内容执行if操作,以决定是否处理它-您可以保存它。
var p = Promise.try(function(){
throw new IOError("Hello");
}).catch(IOError, function(e){
console.log('Only handle IOError, do not handle syntax errors');
});您还可以使用.error来处理源自代理API的OperationalError。通常,OperationalError表示可以恢复的错误(与程序员错误相比)。例如:
var p = Promise.try(function(){
throw new Promise.OperationalError("Lol");
}).error(function(e){
console.log('Only handle operational errors');
});这样做的好处是不会使代码中的TypeError或语法错误静默,这在JavaScript中可能会很烦人。
https://stackoverflow.com/questions/25035019
复制相似问题