I've been reading about jQuery deferreds and promises and I can't see the difference between using .then()
& .done()
for successful callbacks. I know Eric Hynds mentions that .done()
and .success()
map to the same functionality but I'm guessing so does .then()
as all the callbacks are all invoked on a completion of a successful operation.
Can anyone please enlighten me to the correct usage?
Many thanks
The callbacks attached to
done()
will be fired when the deferred is resolved. The callbacks attached tofail()
will be fired when the deferred is rejected.Prior to jQuery 1.8,
then()
was just syntactic sugar:As of 1.8,
then()
is an alias forpipe()
and returns a new promise, see here for more information onpipe()
.success()
anderror()
are only available on thejqXHR
object returned by a call toajax()
. They are simple aliases fordone()
andfail()
respectively:Also,
done()
is not limited to a single callback and will filter out non-functions (though there is a bug with strings in version 1.8 that should be fixed in 1.8.1):Same goes for
fail()
.deferred.done()
adds handlers to be called only when Deferred is resolved. You can add multiple callbacks to be called.
You can also write above like this,
deferred.then()
adds handlers to be called when Deferred is resolved, rejected or still in progress.