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]);
  }
});
4
  • see if this helps: stackoverflow.com/a/14352218/9386929 Commented May 7, 2019 at 18:42
  • who disappeared the previous answer and discussion about that answer? Did not know that could happen in SO Commented May 8, 2019 at 21:36
  • I deleted my own answer since it doesn't provide the right solution. Commented May 9, 2019 at 13:15
  • Odd, I thought once it had comments it could not be deleted. Guess I was wrong. Commented May 9, 2019 at 23:55

1 Answer 1

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();
  }
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.