3

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]);
    });
}

1 Answers1

4

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

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143