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

187
Vistas
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 Respuestas
Responde la pregunta

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 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