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

158
Vistas
How to asynchronously process a dynamically sized array dependent on the fetch responses?

The following code works but is slow because I need to await each response instead of asynchronously processing the responses as they come in.

I imagine there is a way to do this with promises.all() but can't come up with a solution.

  let relatives = [ancestor];
  while (relatives.length > 0) {
    const nextRelative = relatives.pop();
    await fetchRelatives(nextRelative).then(relative => {
      relatives = relatives.concat(relative.ancestors);
    });
  }

We can assume the order is not important, as long as we process the entire tree.

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

0

You can use promises:

Promise.all( relatives.map( task => fetchRelatives(task) ) ).then( results => {
    console.log('all responses:', results)
})

Or

var results = await Promise.all( relatives.map( task => fetchRelatives(task) ) )

if relatives is added dynamically, then this should work:

var do_task = async( relative ) => {
    if (relative) 
        relatives.push(... relative.ancestors)
    
    if (relatives.length)
        return fetchRelatives( relatives.pop() ).then( person => do_task( person ) )
}

/// 4 workers:
Promise.all( Array(4).fill().map( do_task ) ).then(() => console.log('all done'))
about 4 years ago · Juan Pablo Isaza Denunciar

0

if The order of the answers is important to you. You have no choice but to use the async/await or generator functions.

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