简体   繁体   中英

Handle Case when only one out of the two ajax request got successfully executed

I am making two ajax requests. I am able to handle the case when both the ajax request got successfully executed using jquery deferred objects. Now I want to handle the case when one gets success and the other gets failed.

usedCarPurchaseInqPromise and hitRecoApi are the two jquery deferred objects.

CODE :

var usedCarPurchaseInqPromise = D_buyerProcess.buyerProcessApis.processUsedCarPurchaseInquiries(boxObj, leadData);
usedCarPurchaseInqPromise.always(function () {
    if (isFromCaptcha == "1")
        isFromCaptcha = "0";
    if (isGSDClick == "1")
        isGSDClick = "0";
    hideBuyerForm(boxObj);
    $('#newLoading').hide();
    boxObj.find('#pg-process_img,#pg-loadingImg').hide();
    boxObj.find("#loadDetails").hide();
}).fail(function () {
    D_buyerProcess.sellerDetails.processLeadFailureResponse(boxObj, jqXHR);
});
var hitRecoApi = $.ajax({
    type: 'GET',
    url: stockRecommendationsUrl_g,
    headers: { "sourceid": "1" },
    dataType: 'json'
});

$.when(usedCarPurchaseInqPromise, hitRecoApi).done(function (response, jsonData) {
    Common.utils.lockPopup();
    if (D_buyerProcess.utils.isNumberChanged(buyersMobile)) {//if user has changed number as compared to previously stored number in cookie, remove the finance offer of previous number
        if (typeof (customerFinanceUI) !== 'undefined' && typeof (customerFinance) !== 'undefined') {
            customerFinanceUI.hideFinanceOffer();
            customerFinance.removeFinanceOffer(); // removes finance cookie and storage
        }
    }
} 

What you can do is wrap you $.ajax calls into a function that returns a promise and handle it something like this:

let p1 = promiseAjax1()
           .then(result => {result: result, err: null})
           .catch(err => {result: null, err: err})

let p2 = promiseAjax2()
           .then(result => {result: result, err: null})
           .catch(err => {result: null, err: err})

Promise.all([p1, p2])
    .then(results => {
         p1response = results[0];
         p2response = results[1];
         // here you can check for errors in p1response or p2response, by checking eg if p1response.err == null
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM