28

I am trying to understand the difference between

$.when(...).then(...)

$.when(...).done(...)

in jQuery. As far as I understood both of them executes when objects inside when are finished loading. But what is the difference. Examples will be really appreciated.

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • 1
    possible duplicate of [jQuery deferreds and promises - .then() vs .done()](http://stackoverflow.com/questions/5436327/jquery-deferreds-and-promises-then-vs-done) – Raphaël Althaus Jan 10 '13 at 13:38

1 Answers1

32

.done() has only success callback.

.then() has both success and fail callbacks.

As of jQuery 1.8, the deferred.then() method returns a new promise that can filter the status and values of a deferred through a function, replacing the now-deprecated deferred.pipe() method.

The deferred.done() method accepts one or more arguments, all of which can be either a single function or an array of functions.

Since deferred.done() returns the deferred object, other methods of the deferred object can be chained to this one, including additional .done() methods. When the Deferred is resolved, doneCallbacks are executed using the arguments provided to the resolve or resolveWith method call in the order they were added.

Gurpreet Singh
  • 20,907
  • 5
  • 44
  • 60
  • yes, you can use it for fail callback. deferred.then( doneCallbacks, failCallbacks ) – Gurpreet Singh Jan 10 '13 at 13:47
  • 21
    This isn't really correct. Yes, `.then()` has a method signature that allows passing a fail callback as well as a success one. The more important point is that `.then()` returns a **new** promise object, `.done()` returns the same promise object. That's the basic answer at least. For a more complete answer see the answer on [this question](http://stackoverflow.com/questions/5436327/jquery-deferreds-and-promises-then-vs-done) as linked by Raphael to the original question – Anduril Nov 06 '14 at 10:06
  • 2
    A very important difference is what @Anduril commented just above. With `then()` you get a new promise so you can chain different actions. Using this your code can be simplified A LOT. – Andrew Mar 25 '15 at 19:44
  • @Anduril you should make your comment an answer since it contains very important concept. – Benj May 12 '16 at 13:29
  • @Benj at the time perhaps I should have, but Gurpreet has since edited his answer with more information which helps clarify it, and I think it might muddy the water. For now I will leave it as a comment on the original answer – Anduril May 13 '16 at 07:59