我有以下变量:
var userFound = false;
万一这是真的,我想执行以下if语句:
if (userFound) {
//
res.render('pickup/errorAlreadyDelivered', {});
}
但是,问题在于它没有考虑上述for循环内变量的值更改。下面是代码的大部分。
var userFound = false;
let sql = `SELECT box_id, cubby_id, comport, deliveredToUser
FROM recipients
WHERE package_password = ?`;
connection.query(sql, [req.session.sessionUserPackagePassword], function(err, rows, fields) {
if (!err) {
for (var i = 0; i < rows.length; i++) {
// Make the comparaison case insensitive
if ((rows[i].deliveredToUser).toLowerCase() == `no`) {
userFound = true;
var comport = rows[i].comport;
var command = "open" + rows[i].cubby_id;
var commandClose = "close" + rows[i].cubby_id;
var commandStatus = "status" + rows[i].cubby_id;
console.log(command);
console.log(comport);
var options = {
scriptPath: 'python/scripts',
args: [command, comport, commandClose, commandStatus] // pass arguments to the script here
};
PythonShell.run('controlLock.py', options, function(err, results) {
if (err) {
res.render('errorConnection', {});
}
console.log('results: %j', results);
});
}
}
// If the query fails to execute
} else {
console.log('Error while performing Query.');
res.render('errorConnection', {});
}
});
connection.end();
if (userFound) {
//
res.render('pickup/errorAlreadyDelivered', {});
}
任何帮助将不胜感激。
最佳答案
即使if(userFound)行未按此顺序编写,也会在if(userFound)行运行之后运行将userFound设置为true的回调。 connection.query是一个异步函数。尝试将userFound逻辑放入回调中,以便在收到查询结果并将userFound设置为true后运行。
connection.query(sql, [req.session.sessionUserPackagePassword], function(err, rows, fields) {
if (!err) {
for (var i = 0; i < rows.length; i++) {
// Make the comparaison case insensitive
if ((rows[i].deliveredToUser).toLowerCase() == `no`) {
userFound = true;
var comport = rows[i].comport;
var command = "open" + rows[i].cubby_id;
var commandClose = "close" + rows[i].cubby_id;
var commandStatus = "status" + rows[i].cubby_id;
console.log(command);
console.log(comport);
var options = {
scriptPath: 'python/scripts',
args: [command, comport, commandClose, commandStatus] // pass arguments to the script here
};
PythonShell.run('controlLock.py', options, function(err, results) {
if (err) {
res.render('errorConnection', {});
}
console.log('results: %j', results);
});
}
}
// If the query fails to execute
} else {
console.log('Error while performing Query.');
res.render('errorConnection', {});
}
connection.end();
if (userFound) {
//
res.render('pickup/errorAlreadyDelivered', {});
}
});
关于javascript - 在if语句中检索用于比较的值时出现问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43443370/