我正在与Express和MySQL一起工作,并且我希望能够从connection.query
检索数据,然后在同一路线中的其他功能中使用该数据。我希望能够使用app.post中另一个函数内部的connection.query
内部制造的数组,但是我不知道要这样做的最好的方法是什么。我试图使用Express所需的单独文件中编写的实用程序函数,但是我无法将MySQL连接的数据从外部文件中写入的功能中,我什至不确定这是否是适当的方法做我想做的。
这是我的代码,我想做的可能能够将forEach
方法放入其自身函数的内部,然后在查询后在另一个函数中使用返回的数组对其进行操作,依此类推。
app.post('/submit', function(req, res) {
var getPosition = "SELECT ID, position FROM routes";
var posArray = [];
connection.query(getPosition, function(err, results) {
if (err) throw err;
results.forEach(function(item) {
posArray.push(item.position);
return posArray;
}); //end if
});
}); // end app.post
您可以链中间件实现这一目标:
app.post('/submit', getDataFromDatabase, processData); // end app.post
function getDataFromDatabase(req, res, next) {
var getPosition = "SELECT ID, position FROM routes";
var posArray = [];
connection.query(getPosition, function(err, results) {
if (err) throw err;
results.forEach(function(item) {
posArray.push(item.position);
req.posArray = posArray; //attach the data that you want to use later to your req object
}); //end if
next(); //Call the next middleware;
});
}
function processData(req, res, next){
//Do whatever you want with req.posArray;
res.json(posArray); //respond to the client with the posArray (or whatever the client asked for)
}