BloodViolet
BloodViolet

Reputation: 67

How do I keep $.getJSON response in order?

Basically I have a for loop that requests json data

for(var i=0; i<x; i++){
    //does stuff
    $.getJSON(link, function(data){
        // does stuff
        arr.push(file);
    }
}

This will put the files in a random order since getJSON is asynchronous.

So I was wondering, what is the best way to keep the files in order or have them indexed so I'm able to sort them later on?

Upvotes: 1

Views: 112

Answers (2)

Zolt&#225;n Tam&#225;si
Zolt&#225;n Tam&#225;si

Reputation: 12809

You can wrap your AJAX call into a new closure to preserve the variable i, and use the indexed setter signature of your array.

var arr = [];

for (var i=0; i<x; i++){  
    //does stuff
    (function(index) {
        $.getJSON(link, function(data){
            // does stuff
            arr[index] = data;
        }
    })(i);
}

Note, that if you're using EcmaScript 6, you can use the let keyword in you for loop to have a kind of local i variable, so then you don't need the closure.

While this solution solves your issue technically, it's far more elegant and better to use the underlying promises as you can see in @Quentin's answer.

Please note that I did not test this code, it might contain errors, and it's just for demonstrational purposes.

Upvotes: 1

Quentin
Quentin

Reputation: 944157

Put the promises returned by getJSON in an array, and then process the results of the promise.

That way "does stuff" won't happen until all the requests are finished, and the array of promises will resolve to an array with all the data in the right order.

let promises = [];

for (var i = 0; i < x; i++) {
  promises.push($.getJSON(link));
}

Promise.all(promises).then(results => results.forEach(do_stuff_here));

Upvotes: 2

Related Questions