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?