I cannot get the done/fail/always callbacks on each of my ajax requests to execute before the deferred object's callbacks.
The problem I have is that some of my ajax requests may fail, but I need to execute the same code whether one fails or none fail.
Hard to explain exactly, so I made this fiddle to help show the problem I am having. http://jsfiddle.net/zZsxV/
var a1 = $.Deferred();
var a2 = $.Deferred();
var a3 = $.Deferred();
a1.done(function() {
$('body').append('a1 done<br />');
}).fail(function() {
$('body').append('a1 fail<br />');
}).always(function() {
$('body').append('a1 always<br />');
});
a2.done(function() {
$('body').append('a2 done<br />');
}).fail(function() {
$('body').append('a2 fail<br />');
}).always(function() {
$('body').append('a2 always<br />');
});
a3.done(function() {
$('body').append('a3 done<br />');
}).fail(function() {
$('body').append('a3 fail<br />');
}).always(function() {
$('body').append('a3 always<br />');
});
var def = $.when(a1, a2, a3);
def.always(function() {
$('body').append('defer always <-- should be after all<br />');
});
setTimeout(function() {
a1.resolve();
}, 5000);
setTimeout(function() {
a2.reject();
}, 1000);
setTimeout(function() {
a3.resolve();
}, 3000);
I read a lot of the answers on this topic but I don't believe any fit my need exactly.
Any more information needed to help please let me know and I'll add it once I get back. Thanks in advance.
Edit
I do understand what is happening. I just know how to do it to avoid this problem. I tried using .then as well with the same results. Once one request is rejected, it fires the fail callback before waiting for the other callbacks.