0

I placed an asynchronous callback function (something like $.ajax) inside a for loop. It looked more or less like (edit: updated code, see comments):

var i = 0;

for ( ; i < 5; i++ ) {
  (function( index ) {
    $.ajax({
      url: "",
      success: function() {
        console.log( index );
      }
    });
  })( i );
}

It worked, but JSHint gave me a warning saying something like:

"Don't place functions inside loops"

Normally I could just place my callback function outside my loop and call that function for every iteration. Unfortunately I need access to variables, which are assigned inside the loop (e.g. i). So I'm looking for a solution to do something like below:

var i = 0;

function callback( data ) {
  // I want to have access to "i" (0, 1, 2, 3, 4) and the AJAX "data"
  // in this function. But I only have access to "data", because "i"
  // will always be 5
}

for ( ; i < 5; i++ ) {
  $.ajax({
    url: "",
    success: callback
  });
}
mrksbnch
  • 1,792
  • 2
  • 28
  • 46
  • 3
    Well, in your first example, `i` will also be `5` in all callbacks. See [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/q/750486/218196). – Felix Kling Aug 29 '14 at 20:47
  • 1
    Do you have to loop...can't you send one request with all the data? – tymeJV Aug 29 '14 at 20:47
  • Just fix your for loop and add this line to your ajax call `async : false` – Hackerman Aug 29 '14 at 20:54
  • 3
    @RobertRozas uhm... please don't do that. – Kevin B Aug 29 '14 at 20:56
  • @KevinB, i missunderstood the problem, sorry :) – Hackerman Aug 29 '14 at 21:03
  • I mean, it would solve the problem, but... it's definitely not a very good way of doing things. It will result in the clients browser being locked up for a period of time. – Kevin B Aug 29 '14 at 21:04
  • @FelixKling Sorry, you are right. Actually I just took $.ajax as an example. In my case I need to loop over some addresses and geocode (async callback as well) them with Google Maps API. – mrksbnch Aug 29 '14 at 21:08

1 Answers1

2

In this case you can use a function that returns a function that has access to the data you need.

var i = 0;
function callback( i ) {
  return function (data) {
    // I want to have access to "i" (0, 1, 2, 3, 4) and the AJAX "data"
    // in this function.
    console.log(i)
  }
}

for ( ; i < 5; i++ ) {
  $.ajax({
    url: "",
    success: callback(i)
  });
}

however, it would of course be better to submit this data with a single request rather than looping.

Kevin B
  • 94,570
  • 16
  • 163
  • 180