Search code examples
node.jses6-promise

What happens in Node.JS if a Promise runs forever?


Let's say we have this buggy function:

async function buggy() {
  while(true) {
    await new Promise(resolve => setTimeout(resolve, 1000));
  }
}

If you call it somewhere in NodeJS, would it permanently impact the server performances ?

If so, would it be better to always put a fail-safe mechanism like so for all untrusted promises:

new Promise((resolve, reject) => {
  buggy().then(() => resolve);
  setTimeout(reject, 10000);
};

Solution

  • In the case that the promise resolve state depends on an external resource / timer that never ends (Infinity as the duration) the suggested fail-safe would work and the server performance wouldn’t be affected so much.

    // this won’t stuck and the fail-safe will work
    // (ignore the timer not being cleaned)
    function buggy() {
       return new Promise(resolve => setTimeout(resolve, Infinity));
    }
    

    Otherwise (in case the promise is solely synchronous, i.e. the resolve depends on an infinite loop that never ends) the reject function would never get called as the event loop is stuck which will stuck the server.

    // The fail-safe wouldn’t work and the server is stuck
    async function buggy() {
      while(true);
    }
    

    Edit: As pointed out by @Vlaz, in case the buggy function is similar to this:

    async function buggy() {
      while(true) {
        await new Promise(resolve => setTimeout(resolve, 1000));
      }
    }
    

    The fail-safe would work and the server won’t stuck.

    Edit 2: In both cases you won't need a fail safe because if a the fail safe would work it means that the code doesn't stuck the Event Loop and also calling reject on the promise doesn't abort the buggy one