[英]node.js flow not correct when getting data from mysql database
I am developing a small program using Node.js, Express and EJS. 我正在使用Node.js,Express和EJS开发一个小程序。
Basically i have a post api route as follows: 基本上我有一个后api路线如下:
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: fetchdata函数执行以下操作:
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(). 但我的问题是,当connection.query首次运行时,它不会进入回调函数,而是直接进入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?
但是当它退出fetchData函数后,它会运行回调函数,该函数在查询后返回行?
Any ideas? 有任何想法吗?
I think it might be to do with the way the api's work? 我认为这可能与api的工作方式有关?
connection.query
is asynchronous, so you'll have to use a callback function to handle the result of the query. connection.query
是异步的,因此您必须使用回调函数来处理查询的结果。
Here's your code slightly modified: 这是你的代码略有修改:
API route: API路线:
app.post('/getJson', function (req, res) {
fetchData(req.body.selectpicker, function(jsonata) {
console.log('jsonData' + jsonData);
res.render('result.ejs', {
html: '<p>' + jsonData + '</p>'
});
});
});
The fetchdata function: fetchdata函数:
function fetchData(tableName, done)
{
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;
connection.query(query, function(err, rows, fields)
{
if (err) throw err;
console.log('The rows are: ', rows);
done(rows);
});
connection.end();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.