我无法访问 MySQL 查询回调中的 comcoming_matches 数组,这是怎么回事?
我在 console.log(upcoming_matches[1]) 上收到“TypeError: Cannot read property '1' of null”错误消息表示变量由于某种原因正在重置的行(猜测,我对 Javascript 不是很有经验)?
var regex = regex code..
while ((upcoming_matches = regex.exec(body)) != null) {
HLTVID = upcoming_matches[1].split("-");
connection.query('SELECT * FROM `csgo_matches` WHERE HLTVID=' + HLTVID[0], function(err, rows, fields) {
if (err) throw err;
console.log(upcoming_matches[1]);
});
}
最佳答案
因为在执行传递给 connection.query
的回调时,while
循环已经完成并且 upcoming_matches
为 null
(因为这是 while
循环停止的条件)。
connection.query
是异步。
参见 Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
关于javascript - 无法在 NodeJS MySQL 中使用全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27239780/