weixin_33697898 2017-11-24 09:55 采纳率: 0%
浏览 9

$。单次申请时

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];
        }
    });

}
  • 写回答

1条回答 默认 最新

  • 胖鸭 2017-11-24 10:06
    关注

    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
    ----
    
    评论

报告相同问题?