繁体   English   中英

jQuery Promise(when> then)不能使用$ .each和$ .ajax遍历数组

[英]jQuery promise (when > then) not working with iterating through array with $.each and $.ajax

我一直在搜索并尝试许多变体,但是没有运气。

我有一系列的用户:

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之后”,这是因为我没有在函数中返回promise ...但是我不知道为什么会这样!

本文是我最接近我的情况的文章,但它与使用$ .each或数组无关... :( jQuery Promise然后在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'
      });
  });
}

但是,请注意,您现在(一旦固定了两个功能)就得到了两个诺言阵列。 $.when()将不处理嵌套,除非您这样做:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM