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

234
Visualizações
How does an async function called with await can block the event loop?

In the following code, the 'Hey, timeout executed!' is only printed after the loop in the longLoop function is finished.

setTimeout(() => console.log('Hey, timeout executed!'), 100);

let longLoop = async () => {
    for (i = 0; i < 1000000000; i++) {
    }
}

let exec = async () => {
    await longLoop();

    console.log('Loop finished')

}

exec()

However, when I change the longLoop to have an await inside it, the 'Hey, timeout executed!' will print as soon as the await in the loop is reached, like in the following:

setTimeout(() => console.log('Hey, timeout executed!'), 100);

let longLoop = async () => {
    for (i = 0; i < 1000000000; i++) {
        await new Promise(r => setTimeout(r, 100));
    }
}

let exec = async () => {
    await longLoop();

    console.log('Loop finished')

}

exec()

Why does in the first example the event loop seems to be blocked even if I call the longLoop from the exec using an await? And why it doesn't get blocked in the second example just by using an await inside the loop?

I'm just starting in JavaScript, so I thought that just by a function being async and being called with an await inside another async function, it would be executed in a way that the event loop would not be blocked. Due to that, I'm having kinda a hard time to understand the flow of execution.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is a case of microtasks vs (macro)tasks. Promises and async/await enter the microtask queue. setTimeout callbacks enter the (macro)task queue. microtasks get run before (macro)tasks (when the stack is empty to be precise), that's why you see the async/await functions get executed before the setTimeout callback

See also: Difference between microtask and macrotask within an event loop context https://stackoverflow.com/a/71195496/4651083

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