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

198
Visualizações
Javascript - why its not possible to make function inside for look synchronous using async/await?

Im sorry for the question since there are already many similar questions. However, I still dont understand. The code below is suppose to show HOW to make a for loop act synchronous. However, as I see it its still not snychronous. The output of the code below is ** 1 2 3 after forEach done **

But I wonder, if we put the await keyword in front of the function, why is the output not:

** 1 after forEach 2 after forEach 3 after forEach done **

? Because result holds one num at a time, waiting for the execution of returnNum.

const asyncFunction = async () => {
  const nums = [1, 2, 3];

  for (const num of nums) {
    const result = await returnAsyncNum(num);
    console.log(result);
  }

  console.log('after forEach');
}

const returnAsyncNum = x => {
  return new Promise(resolve => setTimeout(resolve, 500, x));
}

asyncFunction().then(() => {
  console.log('done');
})

almost 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The console.log('after forEach') will only execute once the for is fully completed. That does makes sense since you are letting it after the for of, doesn't it?

If you put a console.log before the resolve(x), you will see how the code is waiting for the promise to return the number.

almost 4 years ago · Santiago Trujillo Relatório

0

That's point of async functions, they allow you to write async code as if it were sync.
You are waiting for the promise to complete and get its value.
Since you are waiting for the Promise, the execution of the async function stops in the await and when the Promise fulfills you get its value and the execution continues.

Also your expected output does not make any sense, console.log('after forEach') can only log once by calling the function once.

almost 4 years ago · Santiago Trujillo 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