【问题标题】:passing data from .when to .then in jQuery在 jQuery 中将数据从 .when 传递到 .then
【发布时间】:2016-05-01 07:16:04
【问题描述】:

我正在尝试使用.when.each 来循环一些元素,然后.then 对结果做一些事情。但我不确定如何存储来自.when 的结果以在.then 中使用。

例如

var widget_data = [];

$.when(
    $.each(widget_ids, function(index, widget_id){
        $.get('/widget/' + widget_id, function(data){
            widget_data.push(data);
        });
    })
)
    .then(function(){
        console.log(widget_data);
    });

widget_data 数组运行后为空。

【问题讨论】:

  • 那么上述方法发生了什么?
  • 我看到 XHR 请求发生在 console.log 之后,并且 widget_data 为空
  • $.get 中保留一个console.log(data),看看你是否在那里得到data
  • .when 中的 console.log(data) 工作并显示结果数据。似乎.then 立即运行而无需等待.when 完成。
  • 试试.done而不是.then

标签: jquery promise .when


【解决方案1】:

您需要使用.map() 而不是.each()

var widget_data = [];
$.when.apply($,
    $.map(widget_ids, function(widget_id, index) {
      return $.get('/widget/' + widget_id, function(data) {
        widget_data.push(data);
      });
    })
  )
  .then(function() {
    console.log(widget_data);
  });

当您使用.each() 时,它会返回传递给它的数组,因为它不是一个promise 对象,$.when() 会认为它已解决并会调用then 处理程序而不等待ajax 请求完成。

你可以使用$.map()从源数组创建一个promise对象数组,可以像上面那样传递给$.when(),在这种情况下,只有在所有请求完成后才会调用then处理程序 - 但是请注意,结果数组中值的顺序可能与源数组中项的顺序不匹配。

【讨论】:

  • 谢谢!效果很好。对 Gaby 的解决方案有任何想法吗?似乎产生了相同的结果。
  • @waspinator 是一样的,只是用来创建promise数组的api不同
【解决方案2】:

一个问题是when 需要获取deferered 作为参数,而$.each 不返回一个。

var promises = [];
$.each(widget_ids, function(index, widget_id){
    promises.push( $.get('/widget/' + widget_id, function(data){
        widget_data.push(data);
    }) );
});

$.when.apply($, promises);
 .then(function(){
    console.log(widget_data);
});

【讨论】:

  • 谢谢!您和 Arun 的解决方案都有效。对他有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 2015-10-28
  • 1970-01-01
  • 2019-07-26
  • 2022-11-22
  • 2013-01-28
  • 1970-01-01
  • 2016-09-01
  • 1970-01-01
相关资源
最近更新 更多