【问题标题】:Getting status of multiple promises executed asynchronously获取异步执行的多个承诺的状态
【发布时间】:2014-12-23 07:59:47
【问题描述】:

我正在并行执行多个$http 调用(异步)。我的代码逻辑看起来像这样 -

$scope.ids = [1, 2, 3, 4];
var promises = [];
for(var i in $scope.ids){
    promises.push(
        $http.get('http://0.0.0.0/t2/' + $scope.ids[i])
        );
}

$q.all(promises).then(
    function(res){
        console.log(res);
    },
    function(res){
        console.log(res);
    }
);

现在$q.all() 文档这么说

返回一个将通过数组/哈希解决的单一承诺 values,每个值对应同一个索引/键的promise 在承诺数组/哈希中。如果任何一个承诺被解决了 拒绝,这个产生的承诺将被拒绝 拒绝值。

现在,当所有的承诺都通过时,我得到了一个包含 4 个元素的数组的预期响应。

成功 -> 对象[4]

但是,在全部失败的情况下,res 输出只显示失败的那个。

失败 -> 哈希

这是预期的,也是 Angular 文档提到的。

就我而言,我想知道我发出的所有 http 请求的状态,即使它是失败的,我也需要结果。当然 $q.all() 会在其中一个承诺失败的那一刻爆发。我想等到所有的承诺都通过或失败,然后得到结果。我该怎么做?

【问题讨论】:

    标签: javascript angularjs asynchronous angular-promise


    【解决方案1】:

    一个想法是利用promise的错误回调来返回一个有意义的状态:

    function Failure(r) {
        this.response = r;
    }
    
    $scope.ids = [1, 2, 3, 4];
    var promises = [];
    for(var i in $scope.ids){
        promises.push(
            $http.get('http://0.0.0.0/t2/' + $scope.ids[i]).then(
                function(r) {
                    return r;
                },
                function failure(r) {
                    // this will resolve the promise successfully (so that $q.all
                    // can continue), wrapping the response in an object that signals
                    // the fact that there was an error
                    return new Failure(r);
                }
            );
        );
    }
    

    现在$q.all() 将始终成功,返回结果数组。使用result[i] instanceof Failure 检查每个结果。如果此条件为真,则该请求失败 - 获取执行 result[i].response 的响应。 IT 可能需要进行一些调整,但希望您明白这一点。

    【讨论】:

    • 效果很好。谢谢!
    猜你喜欢
    • 2021-01-22
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    相关资源
    最近更新 更多