AngularJS 如果 promise 被通知,最终不会执行

AngularJS finally not executed if promise is notify

在我的 AngularJS 应用程序中,我试图在 $http 调用中使用 finally

这是我的服务

app.service("webResource", function($http, $q) {
    return {
        post : function(url, json) {
            var defer = $q.defer();
            $http.post(url, json)
            .success(function (data, status) {
                if (data!=null) {
                    defer.resolve(data);
                } else {
                    defer.notify("Send notify....");
                }
            }).error(function (data, status) {
                defer.reject({"response":data, "status": status});
            });

            return defer.promise;
        }
    };
});

在我的控制器中我有

$scope.callServer = function() {
    var promise = webResource.post('someurl',$scope.data);
    promise
    .then(
        function(data) {
            alert("Success");
            //Do for success
        },
        function(data) {
            alert("Error");
            //Do for failure
        },
        function(data) {
            alert("Notify");
        }
    ).finally(function() {
        alert("Finally");
    });
};

如果问题得到解决或被拒绝,则说明一切正常。但是,如果它通知它会提醒 "Notify",但不会提醒 "Finally"。这是为什么?

我正在使用 AngularJS 1.4.2 版本

它最终没有进入的原因是因为您可以有多个通知。来自文档:

"notify(value) - provides updates on the status of the promise's execution. This may be called multiple times before the promise is either resolved or rejected."

finally 是一旦 promise 完全完成(resolve 和 reject 都完成了 promise)

https://docs.angularjs.org/api/ng/service/$q#the-deferred-api

.finally 采用以下形式的两个回调:

.finally(callback, notifyCallback)

您目前只将一个回调传递给您的 finally 处理程序,因此您只会在 resolvereject 上触发 alert('Finally!)

.finally 步骤添加第二个回调,您 应该 在执行 deferred.notify.

时看到触发的回调

docs ($q.promiseAPI)