0

I am attempting to use the jquery $.when() function to prevent certain functions from being fired until the ajax completes. I have the below function but the deferred functions are still firing at the same time as the ajax call.

code:

 $.when(cdeckDataStore("param1","param2","param3")).done([function1("param1"),function2("param1")]);


function cdeckDataStore(action,step,checked) {
   return $.ajax({
      type: "POST",
      datatype: "json",
      url: "url/to/api",
      data: {"action":action,"step":step,"data": checked},
      success: function(data) {
        console.log("success");
      }
   });

}

according to the docs function1 and function2 should wait until the ajax returns to fire.

am I missing something?

arrowill12
  • 1,784
  • 4
  • 29
  • 54
  • are you certain the error handler is not getting called? – FlavorScape Aug 06 '14 at 22:13
  • I am seeing "success" in the console. – arrowill12 Aug 06 '14 at 22:14
  • Duplicated of http://stackoverflow.com/questions/21974649/jquery-when-then-also-when-done-not-waiting - You dont need to pass success/error. $.ajax() is a promise. But success/error are not promises. – RaphaelDDL Aug 06 '14 at 22:14
  • You are correct, a failure would still invoke the promise. I got away with ignoring jquery for years until I used angular, which uses jquery under the hood. – FlavorScape Aug 06 '14 at 22:19
  • You're calling the functions in the array, and returning whatever those two functions return to the array passed to done. What you need is an anonymous function that wraps the two functions. – adeneo Aug 06 '14 at 22:23

1 Answers1

1

Nope, according to docs the references passed to .done() will be invoked after $.when() is done.

Whereas you're invoking your functions in place function1("param1")

You could pass a reference to a function using something like:

function1.bind(this, 'param1')
zerkms
  • 249,484
  • 69
  • 436
  • 539
  • thank you, but what about this. http://api.jquery.com/deferred.done/#deferred-done-doneCallbacks-doneCallbacks "A function, or array of functions, that are called when the Deferred is resolved." I am passing an array of functions. – arrowill12 Aug 06 '14 at 22:17
  • @arrowill12: nope, you're passing an array of what functions return. Scroll to examples and compare `done( [ fn1, fn2 ], fn3, [ fn2, fn1 ] )` to your code. You see - they only pass function names (references), but don't call them like `fn1()` – zerkms Aug 06 '14 at 22:19