0

I have a variable number of URL's that I want to make $.ajax(urlx) to and I don't see any examples of how to pass that to $.when. It does not look like .when takes an array, just a list of parameters.

How can I make this work?

var picturesArray = [];
var urlCount = 2;
$.when(
  $.ajax(urls[0]),
  $.ajax(urls[1])
).done(function() {
  var cntx;
  for (cntx = 0; cntx < urlCount; cntx++) {
    picturesArray.push(arguments[cntx][0]);
  }
});
Pete
  • 3,111
  • 6
  • 20
  • 43

1 Answers1

0

I did finally get it working. The answer is this, though with a few more details.

var requests = [];
for (i = 0; i < urls.length; i++) {
  requests.push(
    $.ajax({
      urlIndex: i,
      url: urls[i],
      success: function(data, textStatus) {
        jsonResult[this.urlIndex] = {
          data: data,
          status: textStatus,
          error: "",
          viewed: false
        };
        console.log("success:" + new Date().getMilliseconds());
      },
      error: function(jqXHR, textStatus, errorThrown) {
        jsonResult[this.urlIndex] = {
          data: {},
          status: textStatus,
          error: errorThrown,
          viewed: false
        };
        console.log("error:" + new Date().getMilliseconds());
      }
    })
  );
}
$.when.apply(undefined, requests).then(
  function() {
    callback();
  },
  function() {
    callback();
  }
);
Pete
  • 3,111
  • 6
  • 20
  • 43