javascript - jQuery promise (当 > 然后)不使用 $.each 和 $.ajax 迭代数组

标签 javascript jquery arrays ajax asynchronous

我一直在寻找并尝试很多变体,但没有运气。

我有一组用户:

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

无论我尝试什么,我总是首先得到“after getStatuses”,我收集这是因为我没有在我的函数中返回 promise ......但我不知道为什么会出现这种情况!

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

我真的很感激任何人都可以对我的问题提供的任何帮助/启发。

谢谢!

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

感谢大家的回复,希望能有解决办法!

最佳答案

$.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(...)

或者安排两个函数从它们的数组中返回一个 promise :

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

关于javascript - jQuery promise (当 > 然后)不使用 $.each 和 $.ajax 迭代数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35408719/

相关文章:

javascript - JavaScript 表单中耗时计算

javascript - jQuery 只允许在 .ajax() 之前单击一次

javascript - html download 属性重定向到 url 而不是下载

c++ - xcode\377 倒置 '?'

arrays - Ruby 可枚举 - 查找最多 n 次匹配元素

javascript - 不明白这里发生了什么;带有 jQ​​uery 对象的匿名函数

javascript - 可以打开和关闭div,但无法再次打开

Java无限数组

javascript - 如何正确使用Js和关联数组插入字符串?

javascript - 如何在javascript中呈现数据?