YouTip LogoYouTip

Misc Deferred Promise

# jQuery deferred.promise() Method [![Image 4: jQuery Misc Methods](#)jQuery Misc Methods](#) ## Example Set two timers with random delays, used to resolve and reject a deferred object respectively. $(function(){function asyncEvent(){var dfd = new jQuery.Deferred(); // Resolve after a random time interval setTimeout(function(){dfd.resolve("Hooray"); }, Math.floor(400+Math.random()*2000)); // Reject after a random time interval setTimeout(function(){dfd.reject("Sorry"); }, Math.floor(400+Math.random()*2000)); // Show a "working..." message every half second setTimeout(function working(){if(dfd.state() === "pending"){dfd.notify("working... "); setTimeout(working, 500); }}, 1); // Return the Promise object, the caller cannot change the deferred object return dfd.promise(); }// Attach a done, fail, and progress handler to the async function $.when(asyncEvent()).then(function(status){alert(status+', things are going well'); }, function(status){alert(status+', you failed this time'); }, function(status){ $("body").append(status); }); }) [Try it Β»](#) * * * ## Definition and Usage The deferred.promise() function returns the Promise object of a Deferred. **Note:** 1. The method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal requests. 2. Contains only a set of methods for the deferred object, including: done(), then(), fail(), isResolved(), isRejected(), always(). These methods can only observe the state of a deferred, but cannot change the internal state of the deferred object. 3. deferred.promise() can also accept a target parameter. In this case, the passed target will be assigned the Promise methods and returned as the result, instead of creating a new object. * * * ## Syntax deferred.promise( ) | Parameter | Description | | :--- | :--- | | _target_ | Object type. The object to which the promise methods are bound. | * * * ![Image 5: Example](#) ## More Examples (#) Using the target parameter to promote an existing object to a Promise. * * jQuery Misc Methods](#)
← Misc Deferred ResolvewithMisc Deferred Notify β†’