BrainLikeADullPencil
BrainLikeADullPencil

Reputation: 11653

passing deferred into a jquery function

I'm trying to figure out jQuery's deferred api using the docs together with code that someone else wrote but find it very confusing. I wonder if looking at the functions below, you coudl explain

  1. what is the significance of dfd.resolve. Does it mean that the fadeOut is complete i.e. is it only executed once the fadeOut is complete? Is this passing the deferred object into the jQuery fadeOut function?

  2. what happens when promise.promise(); is returned? Why call promise(); on the promise property?

    Can you please explain this code a little

    hide: function() {
            if (this.el.is(":visible") === false) {
                return null;
            }
            promise = $.Deferred(_.bind(function(dfd) {
                this.el.fadeOut('fast', dfd.resolve)}, this));
            return promise.promise();
        },
    

Upvotes: 2

Views: 1320

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219920

You're right. dfd.resolve is passed as the callback to fadeOut, so that when the fade out is complete, the promise will resolve.

promise = $.Deferred is misleading, since $.Deferred returns a Deferred object, not a promise. Calling .promise() on the deferred will return a promise.

The difference between a deferred and a promise is that the promise is only used for registering callbacks (via always, done, fail, pipe, progress, or then), whereas the original deferred object also has a resolve method.

To summarize: a promise is the same as the original deferred, minus the resolve method (and its related methods). This is used to protect your promise, so that you're the only one with the ability to resolve/reject it. All the caller can do is add callback functions to it.

Here's a quote from the docs:

The deferred.promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request. The Promise exposes only the Deferred methods needed to attach additional handlers or determine the state (then, done, fail, always, pipe, progress, and state), but not ones that change the state (resolve, reject, notify, resolveWith, rejectWith, and notifyWith).


To simplify this, let's remove the underscore binding:

function hide () {
  var deferred = $.Deferred(function(dfd) {
    $('div').fadeOut('slow', dfd.resolve)
  });

  return deferred.promise();
}

hide().then(function () {
  alert('Fade out is done!');
});

Here's the fiddle: http://jsfiddle.net/fDUej/

Upvotes: 5

Related Questions