Problem with POST requests inside a FOR loop in angularjs [closed]

1

I'm starting on Angularjs and Javascript and I'm having trouble with requests to a REST API.

This is my function:

 $scope.exportERP=function(){

      // En primer lugar insertamos los artículos.
      var artUrl = urlERP + "art_m" + apiKeyERP;
      var artUrlFiltro = artUrl + "&filter%5Bref%5D=";
      $scope.dataArt = $scope.art_m;

      // Recorremos los artículos del carrito
      for(i=0;i<$scope.carrito.length;i++){
      // Comprobamos si el artículo contiene accesorios y los insertarmos o actualizamos en la BBDD.
        if ($scope.carrito[i].accesoriosSeleccionados.length > 0){
            //Recorremos uno a uno los accesorios
         for (j =0;j<$scope.carrito[i].accesoriosSeleccionados.length;j++) {  

           $scope.dataArt.name = $scope.carrito[i].accesoriosSeleccionados[j].descripcion.toUpperCase();
           $scope.dataArt.ref = $scope.carrito[i].accesoriosSeleccionados[j].codigo;
           $scope.dataArt.pvp = Math.round($scope.carrito[i].accesoriosSeleccionados[j].puntos * $scope.datosDistribuidor.coeficiente);

           $http.get(artUrlFiltro + $scope.dataArt.ref) //Petición con filtro por referencia del artículo. Nos permite saber si existe ya o no.
              .success(function(accesorio){  // Exíste el accesorio.

                if (accesorio.count == 0){ // No existe el artículo 

                  $http.post(artUrl, $scope.dataArt)
                  .success(function(data){
                    console.log("Accesorio insertado con éxito");
                    console.log(data);
                  })
                  .error(function(err){ // Error la actualizacion del accesorio.
                    console.log(err);
                  }); 

                } 

              }); 
         }
       } 
     }
 } 

But within the last FOR (contains two values) the two GET requests are executed in a row and when the POST is carried out, the last value is always sent. Why do they not run sequentially for each value within the for? I hope you understand me and many thanks in advance.

    
asked by FSanchez 08.08.2017 в 13:21
source

1 answer

2

Both $http.get and $http.post are asynchronous methods that return promises , which means that most likely the values of $scope.dataArt are not what you are waiting for in each round of the for because before the first request get has finished and enter the .success() already there will be Done all iterations of for

UPDATE

You could use the same promises of the methods get and post to wait for each round, I've added some code.

$scope.exportERP=function(){

      // En primer lugar insertamos los artículos.
      var artUrl = urlERP + "art_m" + apiKeyERP;
      var artUrlFiltro = artUrl + "&filter%5Bref%5D=";
      $scope.dataArt = $scope.art_m;

      //----------INICIALIZAMOS LOS PROMISE A RESOLVE---------------//
      var getPromise=new Promise().resolve();
      var postPromise=new Promise().resolve();

      // Recorremos los artículos del carrito
      for(i=0;i<$scope.carrito.length;i++){
      // Comprobamos si el artículo contiene accesorios y los insertarmos o actualizamos en la BBDD.
        if ($scope.carrito[i].accesoriosSeleccionados.length > 0){
            //Recorremos uno a uno los accesorios
         for (j =0;j<$scope.carrito[i].accesoriosSeleccionados.length;j++) {  

          //----------ESPERAMOS HASTA EL RESOLVE DE CADA UNA DE LAS PETICIONES PARA EJECUTAR LA SIGUIENTE---------------//
           $.when(getDef,postDef).then(function(){
                $scope.dataArt.name = $scope.carrito[i].accesoriosSeleccionados[j].descripcion.toUpperCase();
                $scope.dataArt.ref = $scope.carrito[i].accesoriosSeleccionados[j].codigo;
                $scope.dataArt.pvp = Math.round($scope.carrito[i].accesoriosSeleccionados[j].puntos * $scope.datosDistribuidor.coeficiente);

              //----------REINICIALIZAMOS LA VARIABLE CON LA NUYEVA PROMESA---------------//
              getPromise=$http.get(artUrlFiltro + $scope.dataArt.ref); //Petición con filtro por referencia del artículo. Nos permite saber si existe ya o no.
              getPromise.success(function(accesorio){  // Exíste el accesorio.

                if (accesorio.count == 0){ // No existe el artículo 

                  //----------REINICIALIZAMOS LA VARIABLE CON LA NUYEVA PROMESA---------------//
                  postPromise=$http.post(artUrl, $scope.dataArt);
                  postPromise.success(function(data){
                    console.log("Accesorio insertado con éxito");
                    console.log(data);
                  })
                  .error(function(err){ // Error la actualizacion del accesorio.
                    console.log(err);
                  }); 

                } 

              }); 
           });

         }
       } 
     }
 } 

The downside of this is that it is converting asynchronous actions into synchronous actions, and in Javascript this usually does not end well. In the execution of this code, your entire program will be blocked until this action ends.

    
answered by 08.08.2017 в 13:36