2

I'm using Node Promise (native implementation) to chain MySQL queries.

I'm using node-mysql library for MySQL connections.

var mysql = require('mysql');

var db = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'database'
});

The function is pretty simple and returns a Promise:

function query(sql, repl) {
    return new Promise(function(resolve, reject) {
        db.getConnection(function(err, connection) {
            if (err)
                reject(err);
            else {
                connection.query(sql, repl, function(err, rows) {
                    connection.release();
                    if (err)
                        reject(err);
                    else
                        resolve(rows);
                });
            }
        });
    });
}

However, when I run it, the application never terminates.

query('SELECT * FROM `subscriptions` LIMIT 5', []).then(function(rows) {
    console.log(rows);
}, function(err) {
    console.log('MySQL error: ' + err);
});

There is no more code after, but node still doesn't terminate, even though the promise gets resolved.

Could it be because connection.release() is async? I tried using the pool directly and using one single connection instead of a pool.

2
  • The console.log runs? Commented Jan 8, 2016 at 6:23
  • @JaromandaX, Yes it does, and outputs the rows. Commented Jan 8, 2016 at 14:05

1 Answer 1

2

This happens because Node does not terminate until all connections are closed.

Replace connection.release() by connection.destroy() and Node will terminate successfully.

Credit to the developer of node-mysql for the answer.

Sign up to request clarification or add additional context in comments.

1 Comment

led me to figure out my same issue when I wasn't closing MongoDB connections. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.