Getting the status of multiple promises executed asynchronously

I make several calls $httpin parallel (async). My code logic looks something like this:

$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);
    }
);

Now the $q.all()docs say that

Returns one promise that will be resolved using the array / hash of the value, each value corresponding to the promise with the same index / key in the promises array / hash. If any of the promises is resolved using rejection, then this promise will be rejected with the same rejection value.

Now that all the promises go through, I get the expected response of an array containing 4 elements.

Success → Object [4]

However, in the case when everything does not work, the output resshows only the one that failed.

Failure → Hash

, , , Angular.

HTTP-, , , . , $q.all() , promises . , promises , . ?

+4
1

:

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. , - , , , .

+2

Source: https://habr.com/ru/post/1568708/


All Articles