I am running mysql selects from within a loop, for some reason my variables are being overwritten..
My code below:
setInterval(function () {
for (var s in _bots) {
if (_bots.hasOwnProperty(s)) {
var obj = _bots[s];
for (var prop in obj) {
console.log(' ----- ' + _bots[s][prop].channel + ' ----- ');
channel = _bots[s][prop].channel;
cc = s;
dd = prop;
var sql = 'SELECT * FROM `usrs` WHERE cID = ' + connection.escape(_bots[s][prop].channel) + ' LIMIT 1';
connection.query(sql, function(err, results) {
if(results.length != 0) {
console.log('NAME ---> ' + cc);
console.log('MSG_TO ---> ' + dd);
console.log('ID ---> ' + channel);
} else {
//....
}
});
}
}
}
}, 15000)
Problem is that NAME --> MSG_TO --> variables (cc, dd and channel) always hold the last values from the object. For some reason they are overwriten.. Strangely i am not allowed to use for example s and prop inside the mysql select function.
I need a way to be able to use the s and prop inside the mysql select from the loop
Any ideas?
This is expected behavior. Each pass of your for..in loop defines a closure, and all the closures reference the same function scope in their scope chains. While cc, dd, and channel are all variables in this scope, of course you get same output.
If you want different output, you have to bind these variables to the function before their values were changed. Try:
connection.query(sql, function(cc, dd, channel, err, results) {
if(results.length != 0) {
console.log('NAME ---> ' + cc);
console.log('MSG_TO ---> ' + dd);
console.log('ID ---> ' + channel);
} else {
//....
}
}.bind(null, cc, dd, channel)); // bind the values here