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

186
Visualizações
map array to ajax request and wait for all to complete

I'm trying to run an ajax request on each element of an array. Basically a post request to a php server.

But what is the appropriate way to wait for this result to be completed? What is wrong with the code I wrote below? I need the console.log("step2") to print only after all of the ajax requests are completed.

var results = await Promise.all(
    some_array.map(function(val, key){
        return(
            jQuery.ajax({
                type: 'POST',
                url: '<some/link/to/php/server>',
                dataType: 'json',
                data: val.id,
                xhrFields: {withCredentials: true},
                async: true
            }).done(function(response){         
                run_this_code
            })
        )
    })
)
console.log("step2");

Thanks!

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

I don't know how jQuery's ajax works, but you can try this:

var results = await Promise.all(
    some_array.map(function(val, key){
            return jQuery.ajax({
                type: 'POST',
                url: '<some/link/to/php/server>',
                dataType: 'json',
                data: val.id,
                xhrFields: {withCredentials: true},
                async: true
            })
    })
)
console.log("step2");

Also I would use fetch or axios since they are more modern. With fetch it would look something like this

const results = await Promise.all(
  some_array.map((val, key) => fetch('<some/link/to/php/server>', {
    method: 'POST',
    credentials: 'include',
    body: JSON.stringify(val.id)
  }).then(res => res.json()))
)

I used modern JavaScript syntax, but you can use the old one as well

about 4 years ago · Santiago Trujillo 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