简体   繁体   中英

Jquery $.when not waiting for promises to resolve, reject

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 控制台输出

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?

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, aka, $ as the first argument."

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