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

400
Visualizações
What is the impact of await and .then() on the stack?

I'm having trouble understanding the control flow in the following code. The await in the await setTimeout(() => console.log("Await timeout executed"), 0) line seems to yield control back to the main thread, causing 'I am in main()' to be logged to the console. If I remove the await, the order of the output changes -- "The function is done executing" now comes before "I am in the main thread". I understand the rest of the code but don't get what the stack looks like here. Do await and .then() always return control to the caller? If so, how does the program know to put those functions back on the stack? Thanks.

async function test () {
  console.log("Execution starting");

  setTimeout(() => console.log("Timeout executed"), 0);

  await setTimeout(() => console.log("Await timeout executed"), 0);

  Promise.resolve(5).then(function log() { console.log("Hello from the first promise!") })

  console.log('The function is done executing')
}

test()
console.log('I am in main()')

//Execution starting
//I am in main()
//The function is done executing
//Hello from the first promise!
//Timeout executed
//Await timeout executed
about 4 years ago · Juan Pablo Isaza
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