Created
April 27, 2011 16:56
-
-
Save kswedberg/944656 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<entry name="deferred.promise" type="method" return="Promise"> | |
<signature> | |
<added>1.5</added> | |
</signature> | |
<desc> Return a Deferred's Promise object. </desc> | |
<longdesc> <p>The <code>deferred.promise()</code> 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 (<code>then</code>, <code>done</code>, <code>fail</code>, <code>isResolved</code>, and <code>isRejected</code>), but not ones that change the state (<code>resolve</code>, <code>reject</code>, <code>resolveWith</code>, and <code>rejectWith</code>). </p> | |
<p>If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point. Return <em>only</em> the Promise object via <code>deferred.promise()</code> so other code can register callbacks or inspect the current state.</p> | |
<p>For more information, see the documentation for <a href="/category/deferred-object/">Deferred object</a>.</p> </longdesc> | |
<example> | |
<desc>This test creates a Deferred and sets two timer-based functions to either resolve or reject the Deferred after a random interval. Whichever one fires first "wins" and will call one of the callbacks. The second timeout has no effect since the Deferred is already complete (in a resolved or rejected state) from the first timeout action.</desc> | |
<code><![CDATA[// Create a Deferred and return its Promise | |
function asyncEvent(){ | |
var dfd = new jQuery.Deferred(); | |
setTimeout(function(){ | |
dfd.resolve("hurray"); | |
}, Math.floor(Math.random()*1500)); | |
setTimeout(function(){ | |
dfd.reject("sorry"); | |
}, Math.floor(Math.random()*1500)); | |
return dfd.promise(); | |
} | |
// Attach a done and fail handler for the asyncEvent | |
$.when( asyncEvent() ).then( | |
function(status){ | |
alert( status+', things are going well' ); | |
}, | |
function(status){ | |
alert( status+', you fail this time' ); | |
} | |
); | |
]]></code> | |
</example> | |
</entry> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment