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

259
Vistas
Differences between two styles of async/await in JavaScript from a performance perspective

I have come across two common styles of async/await JavaScript code:

 for await (const a of [x1, x2, x3, x4]) 
 { 
   //do stufF
 }

and

 [x1, x2, x3, x4].forEach(async (a) { 
  //do stuff
 }

Are there any performance (or other) advantages to either of these?

edit: Assume that each instance of x is a promise.

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

0

The for loop will not continue to the next entry in the loop until the promise has settled.

The forEach loop will trigger the async function you pass to it for each promise immediately and, assuming you await the promise inside that function, it will go to sleep until the promise resolves.

Given that your variables contain promises, whatever work they are doing is already being done in parallel, so the only decision factor here is if you want to continue their processing in order or as soon as possible.

(async function() {

  const x1 = new Promise(r => setTimeout(() => {
    console.log('Resolve x1');
    r("x1")
  }, 3500));
  const x2 = new Promise(r => setTimeout(() => {
    console.log('Resolve x2');
    r("x2")
  }, 4000));
  const x3 = new Promise(r => setTimeout(() => {
    console.log('Resolve x3');
    r("x3")
  }, 3000));
  const x4 = new Promise(r => setTimeout(() => {
    console.log('Resolve x4');
    r("x4")
  }, 2000));

  for await (const a of [x1, x2, x3, x4]) {
    console.log(`${a} available inside loop`);
  }

})();

(async function() {

  const x1 = new Promise(r => setTimeout(() => {
    console.log('Resolve x1');
    r("x1")
  }, 3500));
  const x2 = new Promise(r => setTimeout(() => {
    console.log('Resolve x2');
    r("x2")
  }, 4000));
  const x3 = new Promise(r => setTimeout(() => {
    console.log('Resolve x3');
    r("x3")
  }, 3000));
  const x4 = new Promise(r => setTimeout(() => {
    console.log('Resolve x4');
    r("x4")
  }, 2000));

  [x1, x2, x3, x4].forEach(async function (a) {
    const value = await a;
    console.log(`${value} available inside loop`);
  });

})();

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