AngularJs $q.all 不会用混合的嵌套承诺来解决

AngularJs $q.all not resolving with mixed, nested promises

本文关键字:嵌套 承诺 解决 混合 all AngularJs      更新时间:2023-09-26

我有一个函数,需要在继续之前测试参数数组的错误。根据项目的不同,测试可能涉及也可能不涉及对服务器的调用。

我已经实现了一系列$q,以确保它们在评估测试结果之前全部完成。我使用 $q.all 返回数组。

我知道所有的承诺都在解决,因为我可以逐步完成每一个并看到解决方案,但由于某种原因,解决方案没有达到最高层。

最上面的 .then:

$scope.BigTest().then(function(result){
 //examine the array of results & then call the function we want to execute
 // we never ever reach here
},
function(error){
  // handle the error
  // we never ever reach here either
});

使用 $q,all() 的函数:

$scope.BigTest = function(){
    var promises = new Array();
    for (var x = 0; x < $scope.testingStuff.length; x ++){
        var temp = $q.defer();
        if ($scope.testingStuff[x].localTestingGoodEnough){
            if (test){
                temp.resolve(true);
            }
            else{
                temp.resolve(false);
            }
        }
        else{
            var getServerStuff = ServerService.testServer($scope.testingStuff[x]);
            getServerStuff.then(function(result){
                // I've debugged through here and know this is successfully happening        whenever necessary, and that the value is appropriate
                temp.resolve(result.value);
            },function(error){
                temp.resolve(false);
            });
        }
        promises[x] = temp.promise;
    }
    return $q.all(promises);
} 

如伪代码中所述,问题在于当测试需要调用服务器时,整个承诺数组永远不会得到解决。

在不需要服务器调用的情况下,集合将按预期解析。

关于为什么这没有解决的任何想法?也许我没有正确使用 $q.all()?

事实证明,我实际上做对了,但是我的代码中有一个错字,其中"BigTest"else语句中的所有内容都用括号括起来:"()"。虽然这没有引发任何错误,但它阻止了服务器调用的解析。删除括号解决了问题。