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

184
Visualizações
Why does nodejs stop execution of while true loop inside async function

I'd like to understand better under what conditions nodejs stops a running process. My guess was that it stops the process when both the stack and the event loop are empty. But the following program only prints hello once, whereas I was expecting it to loop forever, printing hello every second.

(async () => {
  while (true) {
    await new Promise(resolve => setTimeout(() => console.log("hello"), 1000))
  }
})();

How does the while (true) loop interact with the event loop?

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

0

You need to call your resolve() method ,such that loop can proceed further,like below

(async() => {
  while (true) {
    const data = await new Promise(resolve => setTimeout(() => resolve("hello"), 1000))
    console.log(data)
  }
})();

about 4 years ago · Juan Pablo Isaza Relatório

0

You haven't resolved your promise.

Node can tell that there are no more event sources that might make something interesting happen (no more timers are scheduled) so it exits, even though there is an unresolved promise.

Compare this version, which will print hello forever, because the promise is resolved when the timeout completes and a new timeout is scheduled, thus ensuring that there is always something in the event queue, giving Node.js a reason to carry on running your program.

(async () => {
  while (true) {
    await new Promise(resolve => setTimeout(() => {
        console.log("hello");
        resolve();
    }, 1000))
  }
})();

If resolve is not called, then the promise is not resolved, and the await never completes and no new timeout is ever scheduled. The event queue empties and node decides that to go on doing nothing would be futile, so it exits.

about 4 years ago · Juan Pablo Isaza Relatório

0

You haven't mistaken how NodeJS works. Your code just has a bug: resolve never gets called.

If you change it to the following, "hello" prints forever at 1 second intervals:

(async () => {
  while (true) {
    await new Promise(resolve => setTimeout(() => {
      console.log("hello")
      resolve();
    }, 1000))
  }
})();

The reason your code would still end is because, in NodeJS, the resolve function falls out of scope, indicating to the V8 JS engine that the Promise can never resolve. Therefore it ends the async () => {...}, which in turn quits since it's the last function still running.

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