Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use global variable in NodeJS MySQL

I cannot access the upcoming_matches array inside the MySQL query callback, how come?

I'm greeted with a 'TypeError: Cannot read property '1' of null' error message on the console.log(upcoming_matches[1]); line which indicates that the variable is being reset for some reason (a guess, I'm not very experienced with 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]);
    });
}
like image 924
Alexander Henne Avatar asked Jul 12 '26 03:07

Alexander Henne


1 Answers

Because at the moment the callback passed to connection.query is executed, the while loop already finished and upcoming_matches is null (because that's the condition for the while loop to stop).

connection.query is asynchronous.

See Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

like image 179
Felix Kling Avatar answered Jul 14 '26 17:07

Felix Kling