user8446641
user8446641

Reputation: 1

How to get the data out of ajax requests in a for loop?

The structure of my program is as follows:

var output = [];  //<---- where I want to store the data 

function getData(){
    for(...){
        $.getJSON("...", function(data){
            if(...){
                output.push(data[...]);
            }else{
                $.getJSON("...", function(data2){
                    output.push(data2[...]);
                });
            }
        });
    }
}

This doesn't work due to what I understand to be the async nature of the ajax calls. I can't access the data after calling the function. Doing output[0] returns undefined.

Upvotes: 0

Views: 114

Answers (1)

Burak Can
Burak Can

Reputation: 64

You can initiate the requests in a loop synchronously but you have to listen for the responses asynchronously. jQuery's getJSON method returns a jqXHR object which is Promise compatible. So, you can use Promise.all like this:

function getData() {
  var requests = [];

  for (...) {
    const request = $.getJSON(...);
    requests.push(request);
  }

  return Promise.all(requests);
}

getData().then(function (results) {
  // results is an array with responses of your requests (ordered by push order)   
});

Upvotes: 1

Related Questions