Ajax nested requests

1

I need to make 2 requests $.ajax() nested, where the second depends on the delivered value of the first ... in other words the result of the first enters a loop and for each record found makes a new request . Something like this:

function mostrarInventarioOc() {

    var urlPrincipal = $("#urlPrincipal").val(); // url base
    var valor = $("#ocompra_id").val(); // id a buscar

    $.ajax({
        url: urlPrincipal+"detalle/buscarDetalleOC/"+valor+"/", 
        success:function(respuesta){
            var detalle = eval(respuesta);

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

                    $id = detalle[i]["id_pieza"]; // capturo id a buscar

                    $.ajax({
                        url: urlPrincipal+"bodega/stockBodega/"+id+"/",
                        success:function(result){
                            alert(result['cant_inventario']);
                            // aquí voy a imprimir los datos de la primera y       segunda petición
                        }
                    });
               }
           }
     });
 }

I have read that this is much easier with promise javascript, but I have not managed to do it.

    
asked by Cristian Slater 29.10.2016 в 12:49
source

2 answers

1

I do not see it as complicated, I just think that if you want to see it easier, put your second request in a function to make the code more understandable.

function mostrarInventarioOc() {
    var urlPrincipal = $("#urlPrincipal").val(); // url base
    var valor = $("#ocompra_id").val(); // id a buscar
    $.ajax({
        url: urlPrincipal+"detalle/buscarDetalleOC/"+valor+"/", 
        success:function(respuesta){
            var detalle = eval(respuesta);
                for (var i = 0; i < detalle.length; i++) {
                    mostrarDetalleInventario(detalle[i]["id_pieza"], respuesta);          
                }
           }
     });
 }
 function mostrarDetalleInventario(id,datosDelaPrimera){
    $.ajax({
               url: urlPrincipal+"bodega/stockBodega/"+id+"/",
               success:function(result){
               alert(result['cant_inventario']);
               // aquí voy a imprimir los datos de la primera y       segunda petición

                  }
           });
 }
    
answered by 29.10.2016 в 16:29
1

I would recommend using Promises, because the code in general can be cleaner and readable. I leave you an option using the Bluebird library, it would look something like this:

function request(url){
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  return new Promise(function(resolve, reject){
    xhr.addEventListener("load", resolve.bind(null, xhr.responseText), false);
    xhr.addEventListener("error", reject, false);
  })
}


function mostrarInventarioOc() {

    var urlPrincipal = $("#urlPrincipal").val(); // url base
    var valor = $("#ocompra_id").val(); // id a buscar
  
    request(urlPrincipal+"detalle/buscarDetalleOC/"+valor+"/")
      .then(function(respuesta){
        var detalle = JSON.parse(respuesta);
        return Bluebird.all(
          respuesta.map(function(r){
            return request(urlPrincipal+"bodega/stockBodega/" + r['id_pieza']);
          })
        )
        .then(function(results){
          results.forEach(function(result){
            alert(result['cant_inventario']);
          });
        })
      })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.4.6/bluebird.core.min.js"></script>
    
answered by 29.10.2016 в 13:51