JavaScript – Asynchronous events while looping.

I’m running into a small issue while trying to loop asynchronous events. In my case I was trying to shorten the amount of typing done to send 5 different AJAX request to the server, where as the only difference in the request is an ID which should always be 1-5.

Below is my code showing this, please note that I am using AngularJS so I’m using their post method.

function loopRequest($http, destination) {
    for(var i = 1; i < 6; i++) {
        // Attempt to preserve the value of i throughout the asynchronous call
        var tmp = i; 

        $http.post("http://localhost/test.php", {slot: tmp}).success(function(data) {
            console.log("AJAX call completed for ID: " + tmp);
        });
    }
}

The result of this execution is the following:

AJAX call completed for ID: 5
AJAX call completed for ID: 5
AJAX call completed for ID: 5
AJAX call completed for ID: 5
AJAX call completed for ID: 5

Obviously I could send the identification number back with the AJAX call however I don’t want to do that and would rather understand what the issue is here before continuing. I understand that the array is continuing before the asynchronous function completes, however in java defining a temporary variable like done above would stay in scope for the remainder of the array’s cycle and be used by the asynchrnous call. Apparently that doesn’t work here.

What should I be doing? I could just write out 5 different calls here, but the idea was to eliminate the need to do so.


Source: ajax

Leave a Reply