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


Question

I have code like this:

var client = new mysql.Client(options);
console.log('Icanhasclient');

client.connect(function (err) {
  console.log('jannn');
  active_db = client;
  console.log(err);
  console.log('hest');

  if (callback) {
    if (err) {
      callback(err, null);
    }

    callback(null, active_db);
  }
});

My problem is that Node terminates immediately when I run it. It prints 'Icanhasclient', but none of the console.log's inside the callback are called.

(mysql in this example is node-mysql.

Is there something that can be done to make node.js wait for the callback to complete before exiting?

1
81
6/22/2011 3:43:36 PM

Accepted Answer

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.

46
12/26/2011 12:59:55 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon