How to prevent Node.js from exiting while waiting for a callback?

Callback is Not Queued

Node runs until all event queues are empty. A callback is added to an event queue when a call such as

  emmiter1.on('this_event',callback).

has executed. This call is part of the code written by the module developer .

If a module is a quick port from a synchronous/blocking version, this may not happen til some part of the operation has completed and all the queues might empty before that occurs, allowing node to exit silently.

This is a sneaky bug, that is one that the module developer might not run into during development, as it will occur less often in busy systems with many queues as it will be rare for all of them to be empty at the critical time.

A possible fix/bug detector for the user is to insert a special timer event before the suspect function call.


You can just issue a setTimeout or a recurring timeout with setInterval.

If you want to check for exit conditions, you can also do a conditional timeout:

(function wait () {
   if (!SOME_EXIT_CONDITION) setTimeout(wait, 1000);
})();

Put this at the end of your code and the console will just wait ... and wait ... until you want it to close.


My solution was to instantiate an EventEmitter, and listen for my custom event.

var eventEmitter = new process.EventEmitter();

then I called eventEmitter.emit from the async callback:

client.connect(function (err) {
    eventEmitter.emit('myevent', {something: "Bla"})
});

The last thing in my script was the eventEmitter.on:

eventEmitter.on('myevent', function(myResult){
  // I needed the result to be written to stdout so that the calling process could get it
  process.stdout.write(JSON.stringify(myResult));
});

Node will then wait until the event handler finishes running.


Based on @Todd's answer, I created a one-liner. Include it in the beginning of your script, and set done = true when you are done:

var done = (function wait () { if (!done) setTimeout(wait, 1000) })();

Example:

var done = (function wait () { if (!done) setTimeout(wait, 1000) })();

someAsyncOperation().then(() => {
  console.log('Good to go!');
  done = true;
});

How does it work? If we expand it a bit:

// Initialize the variable `done` to `undefined`
// Create the function wait, which is available inside itself
// Note: `var` is hoisted but `let` is not so we need to use `var`
var done = (function wait () {

  // As long as it's nor marked as done, create a new event+queue
  if (!done) setTimeout(wait, 1000);

  // No return value; done will resolve to false (undefined)
})();

Here is my two cents:

async function main()
{
    await new Promise(function () {});
    console.log('This text will never be printed');
}

function panic(error)
{
    console.error(error);
    process.exit(1);
}

// https://stackoverflow.com/a/46916601/1478566
main().catch(panic).finally(clearInterval.bind(null, setInterval(a=>a, 1E9)));