I have to make a bunch of JSONP calls, and execute some code after they all finish (or fail).
i.e.:
function finished() {
alert('done!');
}
function method1() {
return $.ajax('http://example.org/endpoint', {
data: {
foo: 'bar'
},
dataType: 'jsonp'
});
}
function method2() {
return $.ajax('http://example.org/endpoint', {
data: {
baz: 'qux'
},
dataType: 'jsonp'
});
}
$.when(method1(), method2()).always(finished);
The only problem is, if any of the requests fail, finished()
will not be called.
I can try and detect if one of the ajax calls fails like so:
function method1() {
var method1_timeout = setTimeout(function() {
// this call has failed - do something!
}, 5000);
var ajax = $.ajax('http://example.org/endpoint', {
data: {
foo: 'bar'
},
dataType: 'jsonp',
success: function() {
clearTimeout(method1_timeout);
}
});
return ajax;
}
But I'm stuck at that point - how do I tell the deferred object that that particular ajax request has failed?
I tried calling the ajax object's error()
method:
var method1_timeout = setTimeout(function() {
ajax.error();
}, 5000);
But no luck.
Any ideas?