Dan
Dan

Reputation: 12096

Run a function after an ajax looped get completes

I'm using ajax to get arrays of points for a googlemap, it works fine apart from I need to call the MarkerClusterer after the final $.get has completed.

If I just place the code after the for loop then it runs before the queued gets have completed and doesn't work correctly.

If I used a callback on the $.get then it will run on each loop which is not what I want either

The code

for (i = 1; i <= <?=$pages;?>; i++) {

    points = [];

    $.get("/mappoints/" + i + "/true", function(data) {

        $.each(data.json_array, function(index, value){

            //do things with data
        });
    }, "json");         
}

//run this code after the queued `$.get`s have **all** completed
console.log("done");
var markerCluster = new MarkerClusterer(map, markers);

I've tried the following within the for but that didn't even run, not too sure why?

if(i == <?=$pages;?>){
    var markerCluster = new MarkerClusterer(map, markers);
    console.log("done");
}

Upvotes: 0

Views: 41

Answers (2)

Kevin B
Kevin B

Reputation: 95022

Simply keep track of how many have completed, and when they've all completed, run your code. Also, don't forget to var your variables to prevent global leakage.

var points, counter = 0, i;
for (i = 1; i <= <?=$pages;?>; i++) {
    points = [];

    $.get("/mappoints/" + i + "/true", function(data) {

        $.each(data.json_array, function(index, value){

            //do things with data

        });
        counter++;
        if (counter === <?=$pages;?>) {
            console.log("done");
            var markerCluster = new MarkerClusterer(map, markers);
        }
    }, "json");

}

A better alternative may be to collect an array of promises and apply them to $.when().

var points, promises =  [], i;
for (i = 1; i <= <?=$pages;?>; i++) {
    points = [];

    promises.push($.get("/mappoints/" + i + "/true", function(data) {

        $.each(data.json_array, function(index, value){

            //do things with data

        });

    }, "json"));

}
$.when.apply(null, promises).done(function () {
    console.log("done");
    var markerCluster = new MarkerClusterer(map, markers);
});

Upvotes: 2

schellingerht
schellingerht

Reputation: 5796

Use $.when and .then

$.when(
// Deferred object (probably Ajax request),

// Deferred object (probably Ajax request),

// Deferred object (probably Ajax request)

).then(function() {

// All have been resolved (or rejected), do your thing

});

Upvotes: 2

Related Questions