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

113
Vistas
Aren't async/await functions put in event loop?

I am very new to asynchronous Javascript and was studying the async/await feature. I have kind of a basic question about the code attached. When I run the code, I think the async function should wait (because of await keyword) and be put in micro-task queue, thus suspending its execution. So, the call stack should execute the main thread's console.log('first') , then print the output of randomFunction() when call stack is empty and micro-task queue starts executing and finally invoke the callback. So I thought the output should've been first, (the random number) and then second. But to my surprise that isn't the case. Can someone please explain why this happened in a simplified manner ?

function randomFunction() {
  //generates a random number and prints it
  const number = Math.floor(Math.random() * 100);
  console.log(number);
}

async function asyncWithCallback(callback) {
  await randomFunction();
  callback();
}

function callback() {
  console.log('second');
}
asyncWithCallback(callback);
console.log('first');

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

0

await first evaluates the expression that follows it, and only then the async function returns (with a promise), suspending the function for later.

So the output of the randomFunction is produced synchronously, and then it proceeds as you describe: "first" is output synchronously as well.

Then the call stack becomes empty and we arrive in the "asynchronous phase": the engine processes the job in the PromiseJob queue, which resumes the async function, which calls callback where "second" is output.

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