3

When my page loads, I make one AJAX call, and then another conditionally upon what is on the page. I want to call a function at the end of both; how do I do it?

var dfd = $.when( $.ajax(...) );

if( $("type").val() == "something" ) {
  dfd.when( $.ajax(...) );
}

dfd.then(function() { 
   // final code
});

I can't find much about adding to $.when "conditionally" or "later" as those search terms are too close to the original purpose of the promise itself, so I just get the standard usage of $.when(a, b).then(c)

Thanks

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Sean
  • 14,359
  • 13
  • 74
  • 124

3 Answers3

8

Your code should look more like this:

var dfd = $.ajax(...);
var dfd2 = $.ajax(...);

var deferreds = [];

if($("type").val() == "something")
    deferreds.push(dfd)

if($("other").val() == "somethingElse")
    deferreds.push(dfd2)

$.when.apply( $, deferreds )
  .then( callback, failureCallback );

ref: https://api.jquery.com/jQuery.when/

Mister Epic
  • 16,295
  • 13
  • 76
  • 147
  • Or rather `var deferreds = [$.ajax(...)];` and then `deferreds.push($.ajax(...))`. He wants to make more than one AJAX call. – gen_Eric Mar 07 '14 at 14:58
  • @RocketHazmat I'm unsure what you mean. You want to init the array with the deferred, and the push the same deferred into it again? I was trying to write the code above such that the OP could easily introduce more deferred objects with more conditions, in case his example was a simplication. If I've missed the boat, please let me know. – Mister Epic Mar 07 '14 at 15:04
  • You want to push 2 deferreds into the array. He's making 2 ajax calls. One outside the `if` and one inside the `if`, both need to be in array. – gen_Eric Mar 07 '14 at 15:05
  • 1
    .apply - that's the missing key! Thanks!! – Sean Mar 07 '14 at 15:21
  • 2
    Notice that the code in this answer does *always make* two ajax calls, but only conditionally *waits* for some of them. – Bergi Mar 08 '14 at 11:05
  • Very true. Depending on the situation, it could make more sense to make the AJAX calls contingent on satisfying some condition. – Mister Epic Mar 08 '14 at 14:32
1

To do what the question calls for, (execute one call, then optionally call the second), Mister Epic's answer can be modified as per below. Basically, I have wrapped the ajax calls inside functions, so that dfd2 is only called if the condition is true.

var dfd = function () { 
   $.ajax(...); 
};
var dfd2 = function () { 
    $.ajax(...); 
};

var deferreds = [];

deferreds.push(dfd())

if($("type").val() == "something")
    deferreds.push(dfd2())

$.when.apply( $, deferreds )
  .then( callback, failureCallback );
kristianp
  • 5,496
  • 37
  • 56
0

I have had success in doing this with the Q.js library; http://documentup.com/kriskowal/q/

$ajax(...).then(function(val){
     if($("type").val() == "something") { return $.ajax(...);}
)};
Ryan Anderson
  • 937
  • 10
  • 23