简体   繁体   中英

AngularJS rejected promise is not calling onRejection for $q.all()

So I have this piece of code:

        var deferred = $q.defer();
        var promises = [];

        angular.forEach($scope.devices, function(device){
            var promise = memberService.InsertDevice(memberId, device).then(function (data) {
                //device inserted
            }, function (rejectData) {
                if (rejectData.Error == "Cannot insert record since it already exists") {
                    alert("The number " + device.PhoneNumber + " already exists. Try with a different number.");
                }
            });

            promises.push(promise);
        });

        $q.all(promises).then(function (data) {
            //perform something on Success
        }, function (data) {
           //perform something on rejection
           //THIS NEVER GETS CALLED EVEN IF I GET THE ALERT FROM THE TOP
        });

Have a look at the last comment. For some reason, even if I get the alert (meaning that something went wrong with one of the calls) the overall rejection never gets called.

Promises give the opportunity to "recover" in your failure, so you have to return a rejection in the error handle for $q.all to know it actually failed. The only delta in the following code is return $q.reject(rejectData);

    var deferred = $q.defer();
    var promises = [];

    angular.forEach($scope.devices, function(device){
        var promise = memberService.InsertDevice(memberId, device).then(function (data) {
            //device inserted
        }, function (rejectData) {
            if (rejectData.Error == "Cannot insert record since it already exists") {
                alert("The number " + device.PhoneNumber + " already exists. Try with a different number.");
            }
               return $q.reject(rejectData);
        });

        promises.push(promise);
    });

    $q.all(promises).then(function (data) {
        //perform something on Success
    }, function (data) {
       //perform something on rejection
       //THIS NEVER GETS CALLED EVEN IF I GET THE ALERT FROM THE TOP
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM