2

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

1 Answer 1

3

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)
      );
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

i don't think so because i can log mods[i] before the api call and that works fine
Doesn't the console log undefined as in my example? Can you log the value of i? I don't know if the api.stalk is asynchronous but if it is then that's your problem.
lol right yes it is asynchronous, so how does one get around this problem
I've updated the answer, can't test it but basically you have an anonymous function returning the callback, when calling the anonymous function you pass in current value of "i" therefor creating a new closure for "i" to be used by the callback.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.