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

202
Visualizações
Jquery 'each' wait for the ajax process to finish then continue the loop

I want to run ajax in every loop of the selected checkbox. However 'jquery each' ignores the ajax process. Completed or not completed the loop will continue. Sorry for my language, hope it's understandable.

Here is an example of the code I made.

$('input[name="options[]"]:checked').each(function() {
  jQuery.ajax({
    url: "www.example.com",
    type: "POST",
    data: {
      name:name
    },
    success: function(data) {
      // do something
    }
  });
});

I have tried using async:false in the ajax option, but the page freezes, and will return to normal after the process is complete.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

So all you have to do with any kind of Promise batches is gather all of them to array and pass to "batch Promises" function. No matter if it's jQuery, Angular or other


// Gather all promises returned from $.ajax
var allPromises = [];

$('input[name="options[]"]:checked').each(function () {
    allPromises.push(
        callAjax($(this).val()
    );
});

$.when(allPromises).then(function () {/* do something after all*/})

function callAjax(name) {
    // Returns promise from $.ajax
    return jQuery.ajax({
        url: "www.example.com",
        type: "POST",
        data: {name: name},
        success: function (data) {/* do something after this call*/}
    });
}

about 4 years ago · Juan Pablo Isaza Relatório

0

Here is an alternative solution using fetch(), as it is available in all modern browsers (no jQuery needed):

const jsrv='https://jsonplaceholder.typicode.com/',
      arr='users,posts,comments'.split(',');
      
Promise.all(arr.map(e=>fetch(jsrv+e).then(r=>r.json())))
       .then(console.log)
.as-console-wrapper {max-height:100% !important}

In this sample script I collect the responses from three Ajax calls to the publicly avaible resource provided by typicode.com: The resulting array then consists of three arrays containing the users, posts and comments. In my demo I simply provide console.log as the processing function. This will of course be different in a real life situation.

fetch can be used with POST too, see here for more details: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch .

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