Search code examples
javascriptpromisetedious

Why does creating a new tedious connection keep my program from finishing?


I'm trying to wrap the tedious MSSQL library API with promises to make it easier to use but whenever I make a new Promise that creates a new tedious SQL connection the program never exits and I'm having trouble figuring out why.

This is a stripped down version of my real code with the bare minimum needed to cause the issue.

const {Connection} = require('tedious');

const connect = () =>
  new Promise((resolve, reject) =>
  {
    const config = {
      userName: '----',
      password: '----',
      domain: '----',
      server: '----',
      options: {
        database: '----',
        port: 1805,
        connectTimeout: 6000,
        readOnlyIntent: true,
        rowCollectionOnRequestCompletion: true,
        encrypt: true
      }
    };
    console.log('Pre new conn');
    // const conn = new Connection(config);
    console.log('Post new conn');
    resolve('Resolved');
  });


connect()
  .then(conn => console.log(`conn: ${conn}`))
  .catch(error => console.log(`Err: ${error}`));

When the connection succeeds I get the following output: Pre new conn Post new conn conn: Resolved If I uncomment the line const conn = new Connection(config); then I get the exact same output, but the program never exits!

I'm using tedious v2.6.4 and I'm running the program with node v8.11.3.


Solution

  • Node.js keeps track of open network connections, running timers and other things like that that might indicate that your node.js program is not yet done with whatever it was trying to do and when it sees that count is non-zero, it does not automatically exit. If you want it exit in that situation, you have three options:

    1. You can close the connections that you are no longer using.
    2. You can call .unref() on those connections to remove them from the count node.js is keeping. If it's a higher level thing like a database connection, you may need to call .unref() on the actual socket itself (which the DB interface may or may not make available to you) or perhaps the database shares it's own .unref() method for this purpose.
    3. You can manually exit your process with process.exit() when you're doing with everything you wanted to do.