Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

188
Vistas
for is adding i++ before performing an entire action, ajax async

The problem is the following, I have an array, I perform a for that traverses this array and for each element inside the array it performs an AJAX request, and even though I put the async: false property, apparently it is still an asynchronous request, which does so that the variable i inside the for loops through everything and only performs the request on the last element of the array.

    for(let i = 0; i < array.length; i++){
        let elemnt = array[i]
        console.log(i)
        $.ajax({
            async: false,
            url: 'https://xxx.xxxxxxxxxx.xxx.xx/'+elemnt,
            type: 'GET',
            success: (data)=>{
                //does something with array element...                   
                }
            })
        }

putting the console.log(i) was then to output:

    0
    *Perform AJAX request with array[0]*
    1
    *Perform AJAX request with array[1]*
    2
    *Perform AJAX request with array[2]*

however it stays:

    0
    1
    2
    *Perform AJAX request with array[2]*

I believe this is all due to Ajax's Asynchronous realization, but I already put async: false, I don't know what else it could be.

Thanks in advance for anyone who can help.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Instead of looping through the array and running ajax in the loop, create a function that ONLY continues when ajax is successful.

In the below example, cur is the position in the array to grab the value from. For the ajax call, I shortened it just for my answer obviously you will need to use your full ajax.

let cur = 0;

function runAjax() {
  $.ajax({
    ......
    success: (data) => {
      if (cur == array.length) {
        console.log("Done!");
      } else {
        cur++;
        runAjax();
      }
    }
  });
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda