$.when
returns a Deferred object for all the multiple ajax calls queried simultaneously.
If everything succeeds .done()
executes and if any one of the url fails .fail()
executes.
How to handle partial success states? (i.e) if 5 urls are passed to $.when
, if 3 succeeds we need to handle success state and it 2 fails we need to handle failure state.
$.when($.getJSON(headerUrl), $.getJSON(tasksUrl), $.getJSON(testingTrackerUrl), $.getJSON(highlightsUrl)))
.then(function(headerData, tasksData,testingTrackerData,highlightsData) {
printData(headerData, tasksData,testingTrackerData,highlightsData);
})
.fail(function(data, textStatus, jqXHR) {
console.error('Got error in '+jqXHR);
});
Try
var request = function (url) {
return $.getJSON(url)
}
, requests = [
headerUrl
, tasksUrl
, testingTrackerDataUrl
, highlightsDataUrl
];
// return array of `resolved` , `rejected` jqxhr objects
$.when(
$.map(requests, function (_request, i) {
return request(_request)
})
)
// do stuff with `resolved` , `rejected` jqxhr objects
.always(function (arr) {
$.each(arr, function (key, value) {
// `success`
value.then(function (data, textStatus, jqxhr) {
console.log(data, textStatus, jqxhr);
printData(data)
}
// `error`
, function (jqxhr, textStatus, errorThrown) {
console.log(jqxhr, textStatus, errorThrown)
})
})
});
jsfiddle http://jsfiddle.net/guest271314/91Lomwr3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With