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

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

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