Promisifying all the things

The previous sections focused on the Deferred and Promise objects and their methods, but we’ve reserved another small surprise for you: the promise() method. The latter is different from the deferred.promise() method that you learned a few pages back. promise() allows you to transform a jQuery object into a Promise object, enabling you to add handlers using the methods discussed in this lesson. The syntax of this method is shown here.

Method syntax: promise
promise([type][, target])
Returns a dynamically generated Promise object that’s resolved once all actions of a certain type bound to the collection, queued or not, have finished. By default, type is fx, which means the returned Promise is resolved when all animations of the selected elements have completed.
Parameters
type(String) The type of queue that has to be observed. The default value is fx, which represents the default queue for the effects.
target(Object) The object onto which the promise methods have to be attached.
Returns
A Promise object.

Based on the description of this method, if the jQuery object in use doesn’t have animations running, it’s resolved right away. Hence, any handler attached is executed immediately. Consider the following code:

$('p')
   .promise()
   .then(function(value) { console.log(value); });

If the paragraphs of the page aren’t running any animations, the function added using then() is executed immediately and the value passed to it is the jQuery object itself.

Let’s now consider a slightly more complex example that involves animations created using the animate() method that you learned about in lesson 8. In this example you’ll create two squares and move them from the left to the right of the page at different speeds, so that the animations will finish at different times. Once both the animations are completed, you’ll alert a success message.

The code to achieve this goal is shown in the next listing and is also available as a JS Bin and in the file lesson-13/promisify.html.

Listing 13.7. Promisifying a jQuery collection

In the code of this listing you animate both squares, but the first animation will last 1500 milliseconds , whereas the second will last 3000 milliseconds . After these animations have been defined, you select both squares using the class name that they share, square, and create a Promise object using the promise() method that we’re covering in this section . Finally, you add a function to execute once both animations are completed . How cool is that?


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *