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?

5
  • are you certain the error handler is not getting called? Commented Aug 6, 2014 at 22:13
  • I am seeing "success" in the console. Commented Aug 6, 2014 at 22:14
  • Duplicated of stackoverflow.com/questions/21974649/… - You dont need to pass success/error. $.ajax() is a promise. But success/error are not promises. Commented Aug 6, 2014 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. Commented Aug 6, 2014 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. Commented Aug 6, 2014 at 22:23

1 Answer 1

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')
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, but what about this. api.jquery.com/deferred.done/… "A function, or array of functions, that are called when the Deferred is resolved." I am passing an array of functions.
@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()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.