简体   繁体   中英

jquery ajax when - parallel ajax call based on condition

Suppose that i have multiple ajax request that need to be called parallel. The ajax request that need to be called is based on condition.

I can do it as below but it seems not feasible and trivial.

if (condition1) {
    $.when(
        apiRequest1();
    ).then(function(result1) {

    });
} else if (condition 2) {
    $.when(
        apiRequest2();
    ).then(function(result1) {

    });
} else if (condition 1 && condition 2) {
    $.when(
        apiRequest1();
        apiRequest2();
    ).then(function(result1, result2) {

    });
}

What i want to achieve is as follow. Concept is as follow but how can it be done?

var apiList = [];


if (condition1) {
    append apiRequest1() to apiList;
}

if (condition2) {
    append apiRequest2() to apiList;
}

if (condition3) {
    append apiRequest3() to apiList;
}

if (conditionN) {
    append apiRequestN() to apiList;
}

if (apiList has value) {
    $.when(
        apiList
    ).then(function (resultN) {

    });
}

Arrays can handle that perfectly fine.

In each if () block, just append your promise to the array:

apiList.push(apiRequestN());

At the end, you need to pass each item as a separate parameter to $.when() :

$.when.apply(null, apiList)

Try maybe this solution:

  var async1 = $.ajax({//call 1
        url:'http://mypage.com',
        success: function(data1){
            //data 1
        }
    });

    ....

    var async2 = $.ajax({//call 2
        url:'http://mypage.com',
        success: function(data2){
            //data2
        }
    });

    $.when(async2, async1).done(function(result2, result1) {
        console.log('done!')
    });
var apiList = [];

if (condition1) {
    apiList.push(apiRequest1());
} else if (condition 2) {
    apiList.push(apiRequest2());
} else if (condition 1 && condition 2) {
    apiList.push(apiRequest1());
    apiList.push(apiRequest2());
}

Promise.all(apiList).then((result1, result2) => {
    //Do your thing with the results
})

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