Jason Wells
Jason Wells

Reputation: 889

jQuery deferred objects

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

Upvotes: 1

Views: 153

Answers (4)

David G
David G

Reputation: 96800

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

.fail(function() {

});

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074148

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

Upvotes: 2

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

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

Upvotes: 2

Alex Wayne
Alex Wayne

Reputation: 187004

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.

Upvotes: 4

Related Questions