Here建议使用 done 方法结束 promises 链,以便重新抛出错误:
The Golden Rule of done vs. then usage is: either return your promise to someone else, or if the chain ends with you, call done to terminate it. Terminating with catch is not sufficient because the catch handler may itself throw an error.
是否适用于AngularJs?我看了一下,框架里好像没有这个方法。
更新:
我查看了代码并发现了以下内容:
try {
if (isFunction(fn)) {
promise.resolve(fn(state.value));
} else if (state.status === 1) {
promise.resolve(state.value);
} else {
promise.reject(state.value);
}
} catch (e) {
promise.reject(e);
exceptionHandler(e);
}
window.onerror = function(e) {
// doesn't come here
}
所以基本上 Angular 还会在 exceptionHandler(e);
中记录来自 promise 处理程序的错误,这样它就不会被忽视。如果需要,默认的 exceptionHandler
的行为可以被覆盖,如 here 所解释的那样.
最佳答案
done()
method on Promises/A+ specification
请注意,Promises 只指定 then
,它没有说明 done
。
Q
recommends to… What about usage in Angular?
Q
不是 $q
! Angular 的 promise 实现中没有 done
方法,所以我建议不要使用它。
Q
的黄金法则不适用于 Angular,它们有很大不同的特性。
Promise 是异步的,因此您不能在回调周围使用 try catch
语句。 done
用于向环境抛出一个不可恢复的、不可捕获的(因此将调用 window.onerror
或 process.onuncaughtexception
)。
如果你想捕获异常,你应该使用带有回调的catch
方法:
$q.reject(new Error()).catch(function(e) {
console.log("does catch an error");
});
要捕获未处理的拒绝(在 promise 链的末尾),您还可以使用 $exceptionHandler
.
关于javascript - Angular 中 Promises/A+ 规范用法的 done() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29628481/