What happens with $q.all() when some calls work and others fail?

Alan2 picture Alan2 · Nov 13, 2013 · Viewed 44.9k times · Source

What happens with $q.all() when some calls work and others fail?

I have the following code:

    var entityIdColumn = $scope.entityType.toLowerCase() + 'Id';
    var requests = $scope.grid.data
      .filter(function (rowData, i) {
          return !angular.equals(rowData, $scope.grid.backup[i]);
      })
      .map(function (rowData, i) {
          var entityId = rowData[entityIdColumn];
          return $http.put('/api/' + $scope.entityType + '/' + entityId, rowData);
      });
    $q.all(requests).then(function (allResponses) {
        //if all the requests succeeded, this will be called, and $q.all will get an
        //array of all their responses.
        console.log(allResponses[0].data);
    }, function (error) {
        //This will be called if $q.all finds any of the requests erroring.
        var abc = error;
        var def = 99;
    });

When all of the $http calls work then the allResponses array is filled with data.

When one fails the it's my understanding that the second function will be called and the error variable given details.

However can someone help explain to me what happens if some of the responses work and others fail?

Answer

Chandermani picture Chandermani · Nov 13, 2013

I believe since the promise library is based on Q implementation, as soon as the first promise gets rejected, the reject callback is called with the error. It does not wait for other promises to resolved. See documentation of Q https://github.com/kriskowal/q. For Q.all this is what is mentioned

The all function returns a promise for an array of values. When this promise is fulfilled, the array contains the fulfillment values of the original promises, in the same order as those promises. If one of the given promises is rejected, the returned promise is immediately rejected, not waiting for the rest of the batch.