0

I am new to node.js and having a problem with a mysql query. I have coped code from this SO answer but it's still giving me 'undefined' as the browser result, instead of the rows from the database. The console prints 'got rows' so the query itself seems to have been successful.

var http = require('http');
var mysql = require('mysql');
var sql = require('./sqltest');
var pool = mysql.createPool({
  connectionLimit : 100,
  host: "my.host",
  port: '3306',
  user: "me",
  database: 'db_name',
  password: "pw"
});

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write("Library is: " + sql.getLibrary(pool) );
  res.end("....done. ");
}).listen(8080); 

and here is the code (sqltest.js) that I have copied / modified from the link :

var pool;

function executeQuery(query, callback) {
    pool.getConnection(function (err, connection) {
    if (err) {
         return callback(err, null);
    }
    else if (connection) {
   
      connection.query(query, function (err, rows, fields) {
        connection.release();
        if (err) {
               return callback(err, null);
        }
        return callback(null, rows);
      })
    }
    else {
        return callback(true, "No Connection");
    }
  });
}

function getResult(query,callback) {
  executeQuery(query, function (err, rows) {
     if (!err) {
        callback(null,rows);
     }
     else {
        callback(true,err);
     }
  });
}

function getLibrary(sqlpool) {
  pool = sqlpool;
  getResult('select * from Library', function (err, rows) {
    if (err) 
      {
       console.log(err);
       return 'db error';
      }
    else {
      console.log("got rows");
      return JSON.stringify(rows);
    }

  });
};
exports.getLibrary = getLibrary;
quilkin
  • 874
  • 11
  • 31
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) Your functions use a callback mechanism and therefore do not return anything. – Heiko Theißen Sep 30 '22 at 14:55
  • yes, thanks, eventually - I'm not using Ajax so had to re-interpret a few things. – quilkin Sep 30 '22 at 16:01

0 Answers0