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

207
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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