I am developing a small program using Node.js, Express and EJS.
Basically i have a post api route as follows:
app.post('/getJson', function (req, res) {
var jsonData = fetchData(req.body.selectpicker);
console.log('jsonData' + jsonData);
res.render('result.ejs', {
html: '<p>' + jsonData + '</p>'
});
});
The fetchdata function does the following:
function fetchData(tableName)
{
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'xxxx',
user : 'xxxx',
password : 'xxxx!',
database : 'xxxxx',
port : 'xxxx'
});
connection.connect(function(err) {
console.log('error' + err);
// connected! (unless `err` is set)
});
var query = "SELECT * FROM " + tableName;
var data = [];
connection.query(query, function(err, rows, fields)
{
if (err) throw err;
data = rows;
console.log('The rows are: ', rows);
});
connection.end();
console.log('datsa' + data);
return data;
}
But my issue is that when the connection.query first runs it doesn't go into it the callback function instead it goes straight to connection.end(). But then after it goes out of the fetchData function it then goes and runs the callback function which returns the rows after the query?
Any ideas?
I think it might be to do with the way the api's work?