1

I'm having a tough time wrapping my head around deferred objects in jQuery.

E.G,

I thought I could use the following syntax, but this is actually running both success and fail when a success happens. I thought fail would only run if the ajax call fails?

checkFoo(widget)
.success(step1, step2)
.fail(alert("failed"));

checkFoo is an AJAX call like so

function checkFoo(widget){
   return $.ajax({
          url: "foo.php",
          data: widget,
          format: json
   });
}
1
  • The success method is deprecated in jQuery 1.8. You should use done instead of success.
    – Brigham
    Dec 27, 2012 at 23:40

4 Answers 4

4

This here is bad:

.success( step1(), step2() )

That will pass the result of executing step1() and the step2() as arguments.

But this here is good!

.success( step1, step2 )

It will pass the functions themselves in to be executed later.

4
  • Thanks for that tip Alex. Any idea on why fail is running even though my ajax call is successful in my above example? Dec 27, 2012 at 23:39
  • You might want to use .then(success, failure) or use .fail(failure).success(success) as, I think, .success(func1, func2) just indicates two things to run when it resolves.
    – Lee Meador
    Dec 27, 2012 at 23:41
  • @JasonWells because of the exact same problem. You are calling alert() and then providing the result as the callback. You need to pass in a function.
    – Alex Wayne
    Dec 27, 2012 at 23:41
  • Good point @AlexWayne so the alert() needs wrapping in a function() {alert(...)}
    – Lee Meador
    Dec 27, 2012 at 23:44
2

Your code

checkFoo(widget)
.success( step1(), step2() )
.fail( alert("checkfoo failed") );

calls step1 and step2 and alert immediately, and passes their return values into the success or fail methods. Exactly like

foo(bar());

...calls bar and passes its return value into foo.

If you want to tell jQuery to call step1 and step2 on success, and do the alert on failure, you pass in function references:

checkFoo(widget)
.success( step1, step2 )      // <== No parens, `step1` refers to a *function*
.fail( function() {           // <== Wrap a function around the alert
    alert("checkfoo failed");
});
1
  • 1
    Thanks T.J, this is what I ended up doing. I also went ahead and changed success to done. Dec 27, 2012 at 23:44
2

You are using them the wrong way..

The .success() and .fail() take callback function as parameters..

so try

checkFoo(widget)
.success( function(){
    step1(); 
    step2();
})
.fail( function(){
    alert("checkfoo failed");
});
0

I think you might want to pass a fhnction expression into fail:

.fail(function() {

});

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.