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

不问归期 提交于 2019-12-10 03:52:30

问题


$.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);
});

回答1:


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/



来源:https://stackoverflow.com/questions/27171161/handling-different-success-and-fail-states-for-multiple-ajax-call-using-deferred

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!