I am writing a backend code using javascript, node and the npm modules 'mysql' and 'request'. I tried to write a module to do a pooling of SQL database connections by different API calls in various files of my project. My module mysqlLib.js:
var mysql = require('mysql');
var pool = mysql.createPool({
host : settings.host_DB,
user : settings.user_DB,
password : settings.senha_DB,
database : settings.DB
});
module.exports.getConnection = function(callback) {
pool.getConnection(function(err, conn) {
if(err) {
return callback(err);
}
callback(err, conn);
conn.release();
});
};
At the end of this module I decided to test with a tester.js file
var mysql = require('./lib/mysqlLib.js');
var request = require('request');
mysql.getConnection(function(err, conn) {
conn.query(query1, function(err) {
conn.query(query2, function(err) {
request.get(url1, function(err, httpResponse, body){
conn.query(query3);
});
});
});
});
In fact, the code did what I wanted it to do: Every time I need to make changes to my database through some middleware in the API that I wrote in any of my files, use the getConnection method of mysqlLib. js to pull a connection from my pool and at the end of use release it back to the pool. What's bothering me is that I noticed something that should be taking this little program to an error and it's not ... See, the'conn.query (query, callback) 'function is asynchronous, that means it does not interrupt the code flow. Thus, I thought that by performing the first invocation of 'conn.query' in tester.js, this function would be executed asynchronously allowing the getConnection callback to come to an end. Should not this mean that the program would terminate the callback and release () the connection that was pulled? I thought I could call the first conn.query but once the callback came to its end and the connection was released I would not be able to perform the other queries nested at first because of the lack of it but they are all being executed without error! I wonder what may possibly be happening, why is the connection only released after all callbacks nested in the getConnection callback?