N Promises angular

2

I have on my controller:

$scope.test= function () {      
    var list = ["var0","var1","var2","var3"];
    var result= 0;

    for (var x=0;x<list.length;x++) { 
    result= result + TestService.loadVariable(list[x])
    }

    $scope.result = result;
}

and my service is:

    loadVariable : function(name) {
        return $http({
             method: 'GET',
             url: "/test/sheet/loadVariable/",
             params: {name: name},
            }).then(function success(response) {
                return response.data;
            }, function error(response) {

            });
    },

The problem is that I always get the result and I think it's because I do not have time to execute the loadvariables methods, any suggestions?

    
asked by sirdaiz 18.10.2017 в 19:08
source

2 answers

4

The service $http returns a pledge so you can use the service $q to wait for the promises to be executed using the method all([]) . This method is to wait for all the promises to be executed and then execute the then() method that dates the responses of each request.

For example, here an ajax is executed according to the number of times it is indexed and see how all the answers are obtained at the end:

angular.module("app",[])
.controller("ctrl", function($scope,$http,$q){
  
  $scope.cargarVariables = function(){
    // variable para guardas las promesas
    var promises = [];
    for(var i =0; i < parseInt($scope.cantidad);i++)
    {
      // cada peticion retorna una promesa, la agregamos al array de las promesas
      promises.push($http.get("https://jsonblob.com/api/jsonBlob/3263204c-b42b-11e7-81b3-cb2653b9ed90"))
    }
    
     // $q.all espera a que se terminen todas y luego ejecuta la funcion then
    $q.all(promises).then(function(respuestas){
      var datas = [];

       // por cada respuesta obtenemos la propiedad data que tiene lo que necesitamos
      for(var i = 0; i < respuestas.length;i++)
      {
        datas.push(respuestas[i].data);
      }
      
       // imprimirmos la data
      console.log(datas);
    });
  }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
<input type="number" placeholder="cantidad de N variables a buscar" ng-model="cantidad" />
<button ng-click="cargarVariables()"> cargar variables</button>
</div>

In your case it would be:

$scope.test= function () {      
    var list = ["var0","var1","var2","var3"];
    var promesas = [];

    for (var x=0;x<list.length;x++) { 
      promesas.push(TestService.loadVariable(list[x]));
    }
    $q.all(promesas).then(function(respuestas){
        console.log(respuestas);// manejas las respuestas de cada peticion
     })
    $scope.result = result;
}
    
answered by 18.10.2017 / 19:50
source
1

You could try it this way:

It is simply adding up the values and giving me an accountant to know when the cycle reaches the end, immediately reach the end the final value is assigned to the required variable.

$scope.test= function () {      
    var list = ["var0","var1","var2","var3"];
    var result= 0;
    var contador = 0;

    for (var x = 0; x < list.length; x++) {  
        TestService.loadVariable(list[x]).then(function(respuesta){
            result = (Number(result) + Number(respuesta))

            contador++;

            if(contador == list.length){
                $scope.result = result;
            }
        });
    }
}
    
answered by 18.10.2017 в 19:21