简体   繁体   中英

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

I've been searching and trying so many variations, with no luck.

I have an array of users:

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

I am wanting to pass these users into 2 APIs (same site, different URLs, for different data sets) with $.ajax:

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

No matter what I try, I'm always getting 'after getStatuses' first, which I gather is because I'm not returning promises in my functions... but I don't know why this is the case!!

This article was the closest I got to my situation, but it doesn't deal with using $.each or arrays... :( jQuery Promise then not working after AJAX

I would really appreciate any help / light that anyone can shed on my problem.

Thank you!

edit Here's a Plnkr to demonstrate my ajax woes: https://plnkr.co/edit/jRAAjXX4zFprUbx1KPlN?p=preview

Thanks for all the replies, and I really hope there's a solution!

$.each doesn't return a value, so there's no point returning one.

Instead of using $.each , use Array.prototype.map (there's no equivalent in jQuery) and return the promise inside the callback, eg

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

However, note that you've now (once you've fixed both functions) got two arrays of promises. $.when() won't handle the nesting, unless you do:

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

Alternatively arrange for the two functions to return a single promise from their arrays:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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