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
-
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?
-
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(); },
You’re right.
dfd.resolveis passed as the callback tofadeOut, so that when the fade out is complete, the promise will resolve.promise = $.Deferredis misleading, since$.Deferredreturns aDeferredobject, 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, orthen), whereas the original deferred object also has aresolvemethod.To summarize: a
promiseis the same as the originaldeferred, minus theresolvemethod (and its related methods). This is used to protect yourpromise, 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:
To simplify this, let’s remove the underscore binding:
Here’s the fiddle: http://jsfiddle.net/fDUej/