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

258
Visualizações
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 Respostas
Responde à pergunta

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