javascript - 无法在 NodeJS MySQL 中使用全局变量

标签 javascript node.js

我无法访问 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_matchesnull (因为这是 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/

相关文章:

javascript - Angular 路由(教程)不工作

node.js - 你能从 expressjs 应用程序调用 shell 脚本吗?

node.js - MongoDB 和 MongoJS - 无法让 runCommand 用于文本查询

javascript - 无法通过 Node.js 找到模块 'lodash.curry'

javascript - 并行开发同步/阻塞和异步/非阻塞库-api 的好方法是什么? (JavaScript)

javascript - 注册100个用户后,Firebase会阻止所有请求

mysql - node.js - 我在破坏我的数据库吗?

node.js - Express - 无法发送重定向,对预检请求的响应未通过访问控制检查

javascript - 如何将此 javascript 变量中的数据提取到字符串中

javascript - 从数组中删除特定对象 - Node.js