【问题标题】:$.when promise object not working [duplicate]$.when 承诺对象不起作用[重复]
【发布时间】:2016-10-23 12:51:24
【问题描述】:

我正在发出并发 AJAX 请求,但在尝试等待所有调用返回时遇到问题,done() 中的 console.log 将结果显示为空数组。 $.when 不等待请求完成。

 var result = []
  var promise = []
  for (i=0;i < array.length;i++)
  {
    _url = "http://example.com"
      var req = $.ajax(
        {
          type: "GET",
          url: _url,
          success: function(request) { result.push(request)         
          } ,
          error: function(request) {  result.push("ERROR BROTHA")              
        }
        });
      promise.push(req)
  }

  $.when(promise).done(function(){
    console.log(result);
  });

【问题讨论】:

  • ES6 解决方案:$.when(...promise).done();
  • @MarcoScabbiolo:如果你使用 ES6,你会写 Promise.all(promise).then(…)

标签: javascript jquery .when


【解决方案1】:

你需要传播数组。 Docs.

$.when.apply($, promise).done(...);

来自文档

jQuery.when( deferreds )

deferreds 零个或多个 Deferred 对象,或纯 JavaScript 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-03
    • 2017-04-29
    • 2016-06-07
    • 2016-06-16
    • 2016-05-07
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多