Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does fail() fired when there's no error in $.when()?

I"m using JQuery v2.0.0

I'm trying to understand the deferred objects and I got an unexpected result. The fail() was fired even though there's no visible or known error here.

function foo1() { alert('testing'); }

$.when(foo1())
  .done(alert('success'))
  .fail(alert('fail'))

Thanks...

like image 403
fletchsod Avatar asked Mar 24 '26 11:03

fletchsod


2 Answers

You must pass your callbacks as functions:

$.when(foo1())
    .done(function() {
        alert('success');
    }).fail(function() {
        alert('fail');
    });

Currently, you're attempting to register the undefined result of immediately calling alert('fail') as your .fail handler.

Although you didn't say so, you will be seeing both the success and fail alerts appearing, which should provide a hint that you did something wrong ;-)

like image 118
Alnitak Avatar answered Mar 27 '26 01:03

Alnitak


Instead of passing a function reference to the done and fail functions you are invoking them

function foo1() {
    alert('testing');
}

$.when(foo1())
    .done(function () {
    alert('success')
})
    .fail(function () {
    alert('fail')
})
like image 42
Arun P Johny Avatar answered Mar 27 '26 01:03

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!