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

165
Vistas
Node JS: execution-time-wise, is generating array of promises and then using Promise.all better than looping and instantly awaiting every task?

Suppose we have an array of objects that we have to upload to a cloud service, the service will do something with each object and the return a result. The service's client library has single function that uploads the object and waits for response. Which code will run faster:

async function extractDataInstantAwait(documents) {
  const results = [];
  for (const doc of documents) {
    results.push(await client.extractData(doc));
  }
  return results;
}
async function extractDataPromiseAll(documents) {
  const results = [];
  for (const doc of documents) {
    results.push(client.extractData(doc));
  }
  return Promise.all(results);
}

As far as I know, Nodejs does not run async code in multiple threads, so one may think that there is no difference between those. But, since every call to client.extractData may have to wait for response, the event loop of Nodejs should switch to next promise, do things there (upload another doc), and repeat. Perhaps, if service is slow at parsing each object, but we know it creates new threads for each operation, we can achieve some sort of concurent speed up?

Is my logic correct?

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

0

Promise.all is faster, because Promise.all lets all the promises run in parallel, so your execution time will be the execution time of the longest promise (or close to it).

If you do it in a loop, the promises are executed one after the other, so your execution time will be the sum of all of the promises' execution times.

If you have to await three promises A, B and C which take respectively 200, 300 and 500 ms. With Promise.all they will run concurrently and you will have to wait for C for 500ms (A and B will have completed before that). With a loop you will have to wait 200ms for A, then wait 300ms for B, then wait 500ms for C, so you'll wait 1000ms in total.

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