Angular $q.all() console.log 输出顺序时间对我来说没有意义

Angular $q.all() console.log output order timing not making sense to me

我有这项服务

angular.module("myApp").service("xhrService", [
    "$q", function($q) {
        var promises = [];

        return {
            push: function(promise) {
                promises.push(promise);
            },
            process: function($scope) {
                $q.all(promises).then(function() {
                    $scope.$emit("loading:dataReady");
                    promises = [];                     
                });
            }
        }
}]);

此代码在父控制器中

$scope.$on("loading:dataReady", function () {
    console.log("Data Ready");
});

此代码在子控制器中

var getEstimatedExpenseTypes = $http.get("api/estimatedExpenseType").then(
    function (response) {
        console.log("getEstimatedExpenseTypes Success");
        $scope.estimatedExpenseTypes = response.data;
    },
    function(response) {
        console.log(response.data);
    }
);


xhrService.push([getEstimatedExpenseTypes]);

xhrService.process($scope);

我遇到的问题是 console.log 没有按照我期望的顺序发生。在 chrome 中,使用此代码,我首先看到 "Data Ready",然后是 "getEstimatedExpenseTypes Success"。不应该反过来吗?

我认为 $q.all().then(...) 代码会 运行 在 all() 中的承诺之后。但是从写入控制台的顺序来看,情况似乎并非如此

这是怎么回事。我没有正确理解它的工作原理

更新:固定$on代码放置

$q.all 需要一系列承诺,上述代码使其成为 array of array 个承诺

xhrService.push([getEstimatedExpenseTypes]); 将数组 [getEstimatedExpenseTypes] 压入数组 var promises = [];

xhrService.push(getEstimatedExpenseTypes); 替换 xhrService.push([getEstimatedExpenseTypes]); 使执行顺序正确。

working fiddle

编辑

如果你想从控制器推送承诺数组,你可以将服务中的推送方法更改为,

push: function(promise) {
    Array.prototype.push.apply(promises, promise);
}

然后你可以这样写

xhrService.push([getEstimatedExpenseTypes]);

编辑

如果你想在你的服务中同时添加单一的和数组的承诺,像这样的东西应该可以工作

push: function(promise) {
    if(Object.prototype.toString.call(promise) == "[object Object]")
        promises.push(promise);
    else if if(Object.prototype.toString.call(promise) == "[object Array]")
        Array.prototype.push.apply(promises, promise);
}

希望这对您有所帮助。