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. Commented 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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for that tip Alex. Any idea on why fail is running even though my ajax call is successful in my above example?
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.
@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.
Good point @AlexWayne so the alert() needs wrapping in a function() {alert(...)}
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 Comment

Thanks T.J, this is what I ended up doing. I also went ahead and changed success to done.
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");
});

Comments

0

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

.fail(function() {

});

Comments

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.