Daniel Sh.
Daniel Sh.

Reputation: 2074

Connection.query to execute

Pretty sure this is a quite noobish node.js/callback question but I can't seem to find the proper code to make it run.

This is how I invoke my node-mysql code:

var utils = require('../../config/database/utils');

exports.getResults = function(callback) {   
  var query = "SELECT * FROM my_table"; 
  utils.exec(query, null, function(err, results){
    if(err){
      console.log(err);
      callback(true);
      return;
    }
    console.log(results);
    callback(false, results);
  });
};

Next is the utils file where I can't get the code work.

var pool = require('./connection');

module.exports = {
getDBConnection: function() {
    pool.getConnection(function(err, connection){
        if(err){
            console.log(err);
            return;
        }
        return connection;
    });
},
endDBConnection: function(connection) {
    connection.end(function (err) {
        if(err) {
            console.log(err); 
            callback(true); 
            return; 
        }   
    });
},
exec: function(query, data, callback) {
    console.log(query);
    this.getDBConnection(function(err, connection){
        if(err){
            console.log('error');
        }
        console.log(connection);
        connection.query(query, data, function(err, results) {
            if(err) {
                callback(err);
            }
            callback(false, results);
        });
        this.endDBConnection(connection);
    });
}
}

Code is getting OK the the exec part since the console.log(query) logs the query. But after that, the code's not running, console.log(connection); doesn't show a thing, and of course the connection.query is also not running.

I'm not sure why this is happening.

Upvotes: 1

Views: 10050

Answers (1)

mscdex
mscdex

Reputation: 106698

Returning a value inside a callback is meaningless. You need to pass in a callback that gets called with the value you want to return:

getDBConnection: function(callback) {
    pool.getConnection(function(err, connection){
        if(err){
            console.log(err);
            return callback(err);
        }
        callback(null, connection);
    });
},

You should also use connection.release() instead of connection.end() since you are using a pool:

endDBConnection: function(connection) {
    connection.release();
},

In exec(), you have the wrong this. It should instead be something like:

exec: function(query, data, callback) {
    console.log(query);
    var self = this;
    this.getDBConnection(function(err, connection){
        if(err){
            console.log('error');
            return callback(err);
        }
        console.log(connection);
        connection.query(query, data, function(err, results) {
            self.endDBConnection(connection);
            if(err) {
                return callback(err);
            }
            callback(null, results);
        });
    });
}

Upvotes: 2

Related Questions