Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling different success and fail states for multiple ajax call using deferred objects in jQuery

$.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);
});
like image 645
user4300143 Avatar asked Nov 27 '14 12:11

user4300143


1 Answers

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/

like image 51
guest271314 Avatar answered Sep 21 '22 21:09

guest271314