Handling various success and failure states for multiple ajax calls using deferred objects in jQuery

$.when returns a $.when object for all simultaneous requests with multiple ajax.

If everything succeeds .done() is executed, and if any of the URLs fails .fail() is executed.

How to handle partial success states? (ie) if 5 URLs are passed to $.when , if 3 succeeds, we need to handle the success state and this will not work, we need to handle the 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); }); 
+7
jquery deferred
source share
1 answer

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/

+6
source share

All Articles