0

I am trying to fetch a table, whose name is defined in another table and return the results.

I have defined a database module with these methods:

var mysql = require("mysql");
var config = require("../config/database.js");

module.exports = {
    pool: mysql.createPool({
        host: config.host,
        user: config.user,
        database: config.database,
        password: config.password,
    }),

    getConnection: function(callback) {
        this.pool.getConnection(callback);
    },

    fetch: function(table, callback) {
        this.getConnection(function(err, connection) {
            if(err) {
                callback(err);
            } else {
                connection.query("SELECT * FROM ??", table, callback);
                connection.release();
            }
        });
    },
};

I am trying to fetch the table and then the "sub" table like so:

db.fetch("foo", function(err, rows) {
    if(err) {
        throw err;
    } else {
        _.each(rows, function(row) {
            db.fetch(row.tbl, function(err, result) { console.log(err, result); });
        });
    }
});

However the inner-fetch callback is never called.

Why is this? I suspected I needed to close the first connection before establishing a second so I tried taking the each loop outside but encountered things becoming out of sync.

Lerp
  • 2,957
  • 3
  • 24
  • 43
  • If you comment out the `connection.release` line in your database module, does the callback fire? Is this an async issue where the query hasn't finished by the time you release the connection on the next line? – Matthew Bakaitis May 01 '14 at 11:10
  • Removing the `connection.release` doesn't work. Yes, it's an async issue, but I added in code to make it wait and discovered that the inner query wasn't being called. – Lerp May 01 '14 at 11:42

0 Answers0