Promises/A+ Angular 中规范用法的 done() 方法

done() method on Promises/A+ specification usage in Angular

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.

的解释进行覆盖

Angular 使用 $q 即:

an implementation of promises/deferred objects inspired by Kris Kowal's Q.

您需要使用 angular 文档中提供的 the Promise API:.finally()、.then() 和 .catch()。

Angular 很好地描述了这种差异:

Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains all the important functionality needed for common async tasks.

看起来 $q 中没有 .done()。

希望它能回答您的问题。

除了 sebastienbarbier 的回答之外,$q angular 服务也绑定到 $digest 循环(angular 在内部运行)并且(对于 $q)执行 . done() 在 Kris Kowal 的 Q.

这可以让您在测试中脱颖而出,其中 $scope.digest() 确保承诺得到完全解决。

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 or process.onuncaughtexception)。

如果你想捕获异常,你应该使用带回调的catch方法:

$q.reject(new Error()).catch(function(e) {
    console.log("does catch an error"); 
});

要捕获未处理的拒绝(在承诺链的末尾),您还可以使用 $exceptionHandler.