0

I found out today that Deferred.then(null,func) and Deferred.fail(func) aren't the same thing in JQuery. In ES6's promise, Promise.then(null,func) and Promise.catch(func) are the same thing, so I was confused by JQuery's functions.

The only difference I know of is this:

$.Deferred().reject().promise()
  .fail(function(){
    return $.Deferred().resolve().promise();
  })
  .then(function(){
    console.log('fail caught error'); // NOT printed
  });

$.Deferred().reject().promise()
  .then(null,function(){
    return $.Deferred().resolve().promise();
  })
  .then(function(){
    console.log('then caught error'); //printed
  });

Are there any other useful differences?

Leo Jiang
  • 24,497
  • 49
  • 154
  • 284
  • It is best to get out of the habit of using any of jQuery's proprietary methods like `.fail()` and `.done()`. They simply don't do what the standards-based `.then()` does. I just decided to use only `.then()` with jQuery. Then, when jQuery does actually finally get more standards-based, I won't have to change much or if I cast any jQuery promises to Bluebird promises, I don't have to change things either. – jfriend00 Jun 08 '15 at 23:05

1 Answers1

0

Yes, the difference between them is that .fail() does return the original promise it was called upon while .then() does construct a new promise which might resolve with a different value.

However, due to jQuery's problematic error handling you won't notice this unless you return a promise from your callback, like you do in your example. It would be much more of a problem if you had compared fail to a standard-adhering catch invocation.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375