Question

I am using node-mysql to save data, after getting a pool there is an event loop running until pool.end() called. I connect to MySQL in a loop, get results in node-mysql callback function, I want to know when all connections completed so that I can cll pool.end().

var mysql = require('mysql');
var pool = mysql.createPool({
    host: 'xxxxxx',
    user: 'xxxxxx',
    password: 'xxxxxx',
    database: 'xxxxxx'
});

aArray.forEach(function(u) {
    pool.getConnection(function(err, connection) {
        if (connection) {
            var i = connection.query(aSQL, function(err, rows) {
            })
        }
        connection.release();
    })
})
Was it helpful?

Solution

You could use something like async or just use a simple counter variable:

var conns = aArray.length;
aArray.forEach(function(u) {
    pool.getConnection(function(err, connection) {
        if (connection) {
            var i = connection.query(aSQL, function(err, rows) {
              if (--conns === 0)
                pool.end();
            });
        } else if (--conns == 0)
          pool.end();
        connection.release();
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top