Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda