vincentsty vincentsty - 1 year ago 129
Ajax Question

$.when apply for single request

I am trying to use

$.when apply
in my code. However, it seems that the format return is different for single and multiple request. How can i cater for it?? I am trying not to have another if else outside of it.

$.when.apply(null, apiRequestList).then(function () {
for (var i = 0; i < arguments.length; i++) {
var value = arguments[0];
}
});


This is what i do not want to do.

if (apiRequestList.length === 1) {
$.ajax({

});
} else {
$.when.apply(null, apiRequestList).then(function () {
for (var i = 0; i < arguments.length; i++) {
var value = arguments[0];
}
});

}

Answer Source

You can simply convert arguments into an array, when the length of apiRequestList is 1:

$.when.apply(null, apiRequestList).then(function() {

    var _arguments = Array.prototype.slice.call(arguments);
    if (Array.isArray(apiRequestList) && apiRequestList.length === 1)
        _arguments = [arguments];

    for (var i = 0; i < _arguments.length; i++) {
        var value = _arguments[i][0];
        console.log(value);
    }
});

Live Example on jsFiddle (since we can't do ajax on Stack Snippets):

function x(a) {
  return $.post("/echo/html/", {
    html: "a = " + a,
    delay: Math.random()
  });
}
function doIt(apiRequestList) {
  $.when.apply(null, apiRequestList).then(function() {

      var _arguments = arguments;
      if (Array.isArray(apiRequestList) && apiRequestList.length === 1)
          _arguments = [arguments];

      for (var i = 0; i < _arguments.length; i++) {
          var value = _arguments[i][0];
          console.log(value);
      }
      console.log("----");
  });
}
doIt([x(1), x(2), x(3)]);
doIt([x(4)]);

Example output (it'll vary because of the Math.random()):

a = 4
----
a = 1
a = 2
a = 3
----
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download