我查过许诺,但找不到,我也不明白。 我知道其他一切都工作,并发送数据到客户端,只是空。 这是因为我无法在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})
})
})
因此,第一个明确的问题是,在一个回调中有一个回调。 这将是我第一次尝试重构:
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
variable