我将使用不同的Id值获取我的数据库两次。但我需要在某处保存这两个查询,然后将它们发送到res.render。我已经尝试保存在数组中,但它返回undefined。
app.post('/searchInventory', urlencodedParser, function(req, res){
con.query("SELECT id FROM products WHERE name LIKE '%" + req.body.keyword + "%'", function(err, result){
data = [];
for(var a = 0; a < result.length; a++){
console.log(a);
con.query("SELECT products.id AS id, products.name AS name, products.price AS price, SUM(enter.quantity) AS quantity FROM products JOIN enter ON products.id = enter.id_prod WHERE enter.id_prod = "+mysql.escape(result[a].id)+";", function(err, results, fields){
// I need to store the query from here
data =+ results
});
}
console.log(data); //Undefined
res.render('inventory', {results: results});
});
})
问题是围绕异步数据库查询需要注意。首先要做的是使其简单易读,这就是创建查询承诺。
function dbQueryPromise(query) {
return new Promise((resolve, reject) => {
con.query(query, (err, results) => {
if(err) return reject(err);
resolve(results);
})
})
}
现在您可以使用此承诺来处理您所需的行为:
dbQueryPromise("SELECT id FROM products WHERE name LIKE '%" + req.body.keyword + "%'")
.then(results => {
const promiseArray = results.map(result => {
return dbQueryPromise("SELECT products.id AS id, products.name AS name, products.price AS price, SUM(enter.quantity) AS quantity FROM products JOIN enter ON products.id = enter.id_prod WHERE enter.id_prod = "+mysql.escape(result.id)+";")
})
Promise.all(promiseArray).then(allResults => { res.render('inventory', { results: allResults})})
})
您可以使用子查询来查询产品而不是查询两次。
con.query("SELECT products.id AS id, products.name AS name, products.price AS price, SUM(enter.quantity) AS quantity FROM products JOIN enter ON products.id = enter.id_prod WHERE enter.id_prod IN ( SELECT id FROM products WHERE name LIKE '%?%') ", req.body.keyword, function( error, result){
console.log(result)
})
另外,data + = result不会堆叠数组。您可以使用Array.prototype.concat组合两个数组。
例:
data = data.concat(result)
要么
data = [].concat(data, result)