Making conditional Async calls using Jquery $when

700 views Asked by At

I need to make two async (Second call needs to be made only when some condition is true) calls and when both the calls returns data, I need to make another call. For this I decided to use jquery $when.

Before I make second Ajax call, I need to check some condition. And if its true, then I need to make second ajax call otherwise, there is no need to make second ajax call.

Here is Pseudo-code

 $.when($.get(url, function (result, status, xhr) {
        myresult = result;
    })),
    (
        //If XYZ === 10
          //Make second Ajax call only if condition is true

    ).then(function (r1, r2) {
        //DO something

     });

How can I achieve this ?? With Jquery or any other library ??

3

There are 3 answers

0
Benjamin Gruenbaum On
var first = $.ajax(...);
var second = (condition) ? $.ajax(...) : $.Deferred().resolve(); // ajax only on condition

$.when(first, second).then(function(res1, res2){
    // work with res1 and res2, res2 is undefined if no call was made
});
1
KanhuP2012 On

Execute a function after two ajax requests are successful.

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {

  //if both the calls are sucess then only you can reach here.
  //  inside this you can make your third ajax call.

  }
});
1
yajiv On

You can use ternary operator for second ajax call. pass null value if condition is false as second parameter to $.when.

Here is Pseudo-code

$.when(
    //first ajax call ,
    (XYZ===10) ? //second ajax call 
               : null
       ).then(function (r1, r2) {
        //DO something

     });

Hope it helps.

Demo:- jsfiddle.net/NF2jz/5721 (try for a=0 and a=1)