Last week, I was looking up some Promise information in the jQuery API when I came across the .promise() fn-method. While I have worked with promises in the context of AJAX and explicit Deferred objects, it seems that jQuery provides implicit promise functionality around their queues and dequeuing functionality. This allows for promise objects to be returned for animations, which are, after all, nothing more than encapsulated "fx" queues.
By default, the animation methods in jQuery (animate(), slideDown(), slideUp(), etc.) return a reference to the jQuery object (in order to maintain method chaining). And traditionally, if you want to perform an action after an animation is complete, you have to provide some sort of callback as an argument or property of the animation configuration.
With the .promise() method, however, you can get a promise object that will be resolved once the animation is done. This provides for more readable code (in my opinion) with the option for multiple callback handlers. To see what I'm talking about, take a look at the following code. In this demo, we're going to hide and show a DIV and alter the "action text" once the animation has been completed.
As you can see, we are using the .slideToggle() method for animation. However, after we call the slideToggle() method, we are chaining it with the promise() method:
var promise = container.slideToggle().promise();
This returns a promise object rather than the jQuery object. Once we have the promise object, we can start to attach completion handlers using the done() method. This allows us to invoke zero or more callbacks once the animation has completed.
The documentation for the .promise() method doesn't mention anything about fail() outcomes. In my testing, I found that calling stop() on an animation did not trigger a fail() callback handler. However, if I called stop() and included the jump-to-end parameter, the done() callbacks would be invoked. So, it looks as if the only viable callback collection will be that of a successful completion.
Using .promise() with jQuery animation is not revolutionary. It doesn't provide any completely new functionality. What it does provide is a way to define callbacks in an easier, more readable, more flexible way. Also, when you consider the $.when() method, queue-based promise objects make it much easier to coordinate multiple animations.
Want to use code from this post? Check out the license.