2

I'm calling an async function that needs a callback function as parameters.

Here is the javascript code:

for(i in array) 
{
    var item = array[i];
    functionToCall(item[i][1], 50, function(a, b)
    {
        alert(a + b);
    });
}

I cannot edit functionToCall function. What I want to do is using the "item" variable in the callback function like this.

for(i in array) 
{
    var item = array[i];
    functionToCall(item[i][1], 50, function(a, b, c)
    {
        alert(a + b + c);
    }, item);
}

But this code doesn't work properly. I cannot just use "item" inside the function because it is always using the last item in array.

So how can I do that?

Marm
  • 863
  • 2
  • 15
  • 30

3 Answers3

4

You can use item inside the function, but you need to "capture" it so that you don't end up using the last element of the array everytime.

for(var i = 0, l = array.length; i < l; ++i) { // better than for .. in
    var item = array[i];
    (function(item, i){
      functionToCall(item[i][1], 50, function(a, b) // do you really re-index item with the same index?
      {
          alert(a + b);
      });
    })(item, i);
}
Jordão
  • 55,340
  • 13
  • 112
  • 144
0

It's a bad idea to use for..in to iterate arrays. Instead use .forEach() and a lot of your problems just go away:

array.forEach(function(item)
{ 
    functionToCall(item[1], 50, function(a, b) 
    { 
        alert(a + b + item[1]); 
    }); 
}

To use .forEach() in older browsers, see this.

gilly3
  • 87,962
  • 25
  • 144
  • 176
0

I would try something like this:

 function createExecutionCall(itemIndex, number, item)
 {
      return function() { functionToCall(itemIndex, number, function(a, b)
      {
           // Example, item should be contained within this closure then
           alert(a + b + item);
      });
 }

 for(i in array) 
 {
     var item = array[i];

     var call = createExecutionCall(item[i][1], 50, item);
     call();
  }
Tejs
  • 40,736
  • 10
  • 68
  • 86