0

i have in my controller a function that executes some tasks, one of them is to check using my service if some prices or valid, and if there exist any errors stop from executing the rest of the code, the problem is that my variable "error" isnt being updated, basically in my promise when there is a error it increments the error variable, and then after this case there are any errors returns (stop). But cant figure out why isnt updating the variable error.

My code:

function apply(){
 var error = 0;
           if(vm.costPrice){

               vm.name="";


               for (var i = 0; i < vm.costPrice.length; i++) {

                       (function (i) {

                           if (isChecked(vm.costPrice[i].id)) {

                           //create later a service that accepts array of data (less requests = better performance)
                           MyService.validateThings(vm.product.pvp, vm.costPrice[i].discount_price)
                               .then(function (response) {

                                   },
                                   function (response) {

                                    error++;
                                       vm.isErrorCostPrice = true;
                                       if (i > 0) {
                                           vm.name += ' ';
                                       }
                                       vm.name += vm.costPrice[i].condition.name;

                                   });

                           }

                           }(i));

                }

                if(error > 0){
                return;
                }

// Other code above...

}
Marco Santos
  • 915
  • 2
  • 11
  • 24

1 Answers1

0

I'm guessing you mean that at this code:

if(error > 0){
    return;
}

error is always 0.

Since you have a for loop with a promise that executes after some service the code above runs immediately, and your promise runs at a later time. you need to make sure all your promises are done before checking if there are any errors.

You can probably do something as described in an answer on this question: angular $q, How to chain multiple promises within and after a for-loop

Community
  • 1
  • 1
John Boker
  • 82,559
  • 17
  • 97
  • 130