Question

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

Was it helpful?

Solution

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/

OTHER TIPS

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 );

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(...);}
)};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top