【问题标题】:jQuery promise (when > then) not working with iterating through array with $.each and $.ajaxjQuery promise (when > then) 不能使用 $.each 和 $.ajax 遍历数组
【发布时间】:2016-02-16 05:37:12
【问题描述】:

我一直在搜索和尝试这么多变体,但没有运气。

我有一组用户:

var arr = ['tom', 'sally', 'jill', 'sam', 'john'];

我想使用 $.ajax 将这些用户传递到 2 个 API(相同的站点、不同的 URL、用于不同的数据集):

function getStatus1() {
  return $.each(arr, function (index, value) {
    arrStatus.push($.ajax({
        url: 'https://some/url',
        dataType: 'json'
      })
      .always(function (response) {
        console.log('from getStatus1');
      }));
  });
}

function getStatus2() {
  return $.each(arr, function (index, value) {
    arrStatus.push($.ajax({
        url: 'https://some/url',
        dataType: 'json'
      })
      .always(function (response) {
        console.log('from getStatus2');
      }));
  });
}

$.when(getStatus1(), getStatus2()).then(function () {
  console.log('after getStatuses');
});

无论我尝试什么,我总是先得到“getStatuses”,我认为这是因为我没有在我的函数中返回承诺......但我不知道为什么会这样!

这篇文章是我最接近我的情况,但它不涉及使用 $.each 或数组... :( jQuery Promise then not working after AJAX

我非常感谢任何人都可以解决我的问题。

谢谢!

编辑 这是一个 Plnkr 来展示我的 ajax 问题: https://plnkr.co/edit/jRAAjXX4zFprUbx1KPlN?p=preview

感谢大家的回复,我真的希望有一个解决方案!

【问题讨论】:

  • 在成功的ajax响应回调里面尝试push到数组怎么样?
  • 你的 when...then 正在工作,但 ithink 在你的 ajax 调用中存在问题
  • 我也试过了:function getDetails() { return $.each(arr, function (index, value) { arrDetails.push($.ajax({ url: 'some/url' + value, dataType: 'json', 成功: function (response) { console.log('from getDetails'); } })); }); } ...给出相同的结果:(
  • $.each 没有返回值...

标签: javascript jquery arrays ajax asynchronous


【解决方案1】:

$.each 不返回值,因此返回值没有意义。

不要使用$.each,而是使用Array.prototype.map(jQuery 中没有等效项)和return 回调中的promise,例如

function getStatus1() {
  return arr.map(function(value, index) {
      return $.ajax({
          url: 'https://some/url',
          dataType: 'json'
      });
  });
}

但是,请注意,您现在(一旦修复了这两个函数)得到了 两个 的 promise 数组。 $.when() 不会处理嵌套,除非你这样做:

$.when($.when.apply($, getStatus1()), $.when.apply($, getStatus2()).then(...)

交替安排这两个函数从它们的数组中返回一个承诺:

function getStatus1() {
    return $.when.apply($, arr.map(...))
}

【讨论】:

  • 感谢您的回复!我花了很多时间使用它来尝试让我的代码工作......但没有成功。我最终创建了一个 Plnkr plnkr.co/edit/jRAAjXX4zFprUbx1KPlN?p=preview 来展示我的 ajax 困境......主要问题似乎是数组 - 如果数组在 ajax 调用中没有产生“失败”,那么“何时”将输出......但是如果数组产生“失败”,则不输出“何时”。我觉得我学到了很多东西,但也有所收获!
  • @dm400 如果它解决了您的问题,这里通常的做法是“接受”答案:)
  • 谢谢——我仍然无法在“getStatus”输出之后显示“when”输出——当数组生成“失败”时......我最终不得不操作'always' 方法中的数组。无论如何,是的 - 现在接受答案 - 感谢您的帮助。
  • @dm4000 这是$.when 的文档行为 - 如果一个失败,$.when 承诺也会这样做。
  • 啊!这很有帮助——这很清楚为什么代码的行为方式会如此。谢谢!
猜你喜欢
  • 2014-07-19
  • 2016-06-10
  • 2015-03-03
  • 2016-09-25
  • 2010-12-26
  • 2013-11-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
相关资源
最近更新 更多