here is what i've got
var mods = this.registry.gmmods;
for (var i = 0; i < mods.length; i++) {
if(mods[i] != this.config.botid){
this.api.stalk(mods[i],true,function (data){
console.log(mods[i]);
});
}
}
only the console log outputs undefined and i can seem to figure out how to get that data in callback function as the callback data doesn't contain it
could anyone tell me how i might be able to do that
It's a problem with i in your closure, when callback of this.api.stalk is called chances are that i is mods.length. See the following example:
var i = 0;
var arr=["hi","there"];
for(i=0;i<arr.length;i++){
setTimeout(function(){
console.log(arr[i]); //undefined
console.log("and i is:"+i); //i will be 2
},100);
}
Here is how you can solve the closure problem:
var i = 0;
var arr=["hi","there"];
for(i=0;i<arr.length;i++){
setTimeout(
(function(index){
return function(){
console.log("Index is:"+index);//0 and 1
console.log("arr at index:"+arr[index]);//hi and there
console.log("i is:"+i);//2 and 2
console.log("arr at i:"+arr[i]);//undefined and undefined
}
})(i)
,100);
}
Your code could look something like:
var mods = this.registry.gmmods;
for (var i = 0; i < mods.length; i++) {
if(mods[i] != this.config.botid){
this.api.stalk(mods[i],true,
(function(index){
return function (data){
console.log("index is:"+index);
console.log(mods[index]);
console.log("i is:"+i);
console.log(mods[i]);
}
})(i)
);
}
}