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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度