[英]how to get mysql nodejs to send variable after query loads
I have looked up promises but cant figure it out, and i dont understand them.我查过promise,但无法弄清楚,我不明白它们。 I know everything else works and sends data to the client, just empty.
我知道其他一切正常并将数据发送到客户端,只是空的。 and its because i cant assign the variable in time when sql finished?
这是因为我无法在 sql 完成时及时分配变量?
app.post('/api', urlencodedParser,function(req, res,next) {
console.log(req.body);
var data = req.body.productObjs;
var bool;
data.forEach(function(product) {
connection.query(`SELECT * FROM productInfo where specId = ${product.productSpec}`,function(error,rows){
(error,rows)=>{
if (error) {
next('error making the query: ' + error.message)
}
else {
console.log(rows[0]['specId'])
console.log(rows[0]['productPrice'])
if (product.productPrice === rows[0]['productPrice']) {
bool=true
}
if (product.productPrice !== rows[0]['productPrice']) {
bool=false
}
}
})
});
//res.send({"bool":bool})
})
})
So the very first clear issue is that you have a callback within a callback.所以第一个明确的问题是你在回调中有一个回调。 That'd be my first refactoring attempt:
那将是我的第一次重构尝试:
app.post('/api', urlencodedParser, function (req, res, next) {
console.log(req.body);
const data = req.body.productObjs;
let bool;
data.forEach((product) => {
connection.query(`SELECT * FROM productInfo where specId = ${product.productSpec}`, (error, rows) => {
if (error) {
next('error making the query: ' + error.message);
} else {
console.log(rows[0]['specId']);
console.log(rows[0]['productPrice']);
bool = product.productPrice === rows[0]['productPrice'];
}
});
});
});
bool
variablebool
变量的简化条件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.