Skip to content
Advertisement

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement