1

I have a dynamic array of API calls that need to go out. However, jQuery's $.when does not appear to be waiting for promises to resolve or be rejected, or I'm not understanding how to use promises correctly.

Code

function addEntry(data) {
  return new Promise(function(resolve, reject) {
    _customAPIClass_.post('some/url/path', data)
      .done(function(){
        console.log('resolving');
        resolve(1000)
      })
      .catch(function(){
        console.log('rejecting');
        reject(2000);
      })
  });
}

let deferreds = [];

$.each(form.find(el), function(i, element) {
  let data = {
    id: $(element).find('.id').val(),
    name: $(element).find('.name').val()
  }
  deferreds.push(addEntry(data));
}

if (deferreds.length) {
  $.when.apply(deferreds).then(function(data){
    console.log('All done', data)
  }, function(err){
    console.log('error', err);
  });
}

Console output Two api calls rejecting promise after .then() executes console output

So, what I don't understand, and what other questions here on Stack Overflow or on the jQuery docs aren't helping me solve, is why is the .then() acting like everything is OK before the API calls have completed and resolved or rejected their promises? How do I handle resolves or rejects after all API calls have been made, or am I misunderstand the purpose of the .when() and promises?

  • 1
    your `.apply` appears to be missing something quite important. (it takes two arguments) – Kevin B Jun 11 '18 at 15:33
  • any particular reason you're using .apply and not just calling .when() directly? See https://api.jquery.com/jquery.when/ for usage examples. Also note that it still won't wait for everything to finish necessary - as soon as any of the promises is rejected, it'll fire the callback. – ADyson Jun 11 '18 at 15:39
  • @ADyson because $.when doesn't accept an array. – Kevin B Jun 11 '18 at 15:40
  • Ah ok sorry I missed that. – ADyson Jun 11 '18 at 15:41
  • In that case: Possible duplicate of [Pass in an array of Deferreds to $.when()](https://stackoverflow.com/questions/5627284/pass-in-an-array-of-deferreds-to-when) – ADyson Jun 11 '18 at 15:41
  • Ok, so that worked, for the most part. Thanks. Now I just need to figure how to properly handle the errors. – Jonathan Eltgroth Jun 11 '18 at 15:45

1 Answers1

0

Change:

$.when.apply(deferreds)

to:

$.when.apply($, deferreds)

As described here: https://medium.com/sungthecoder/making-multiple-ajax-calls-and-deciphering-when-apply-array-b35d1b4b1f50 and as mentioned in Kevin B's comment:

"When we call $.when() function, ‘this’ keyword inside the function is implicitly bind to jQuery object. But when we call $.when.apply(), we have to explicitly bind ‘this’ keyword to something. And we know that the binding has to be with jQuery object, so we pass jQuery object, a.k.a., $ as the first argument."

JanErikGunnar
  • 211
  • 1
  • 7