Categories
connection-pooling express javascript mysql node.js

NodeJS MySQL How to get the result outside of the query function

I can’t seem to figure out how the get the result outside of a NodeJS MySQL Pool query. Here is some sample code to better explain what I mean.

var result="Hello world!";
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 100,
host : process.env.DB_HOST,
user : process.env.DB_USERNAME,
password : process.env.DB_PASSWORD,
database : process.env.DB_DATABASE
});
pool.query('SELECT * from user LIMIT 10', function (err, rows) {
result = rows;
});
res.send(result);

The above will return ‘Hello world!’ instead of the query.

If I console.log(result) inside the pool.query function it returns the rows from the query but I can’t seem to get the data outside of the function. I’ve logged the function and checked all the associated functions and I think I’m just missing something basic.