我有以下变量:
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', {});
}
任何帮助将不胜感激。
最佳答案
将 userFound 设置为 true 的回调将在 if (userFound) 行运行后运行,即使它们不是按该顺序编写的。 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/