jQuery deferred.promise()Method

jQuery 杂项方法jQuery Miscellaneous Methods

Example

Set two timers with random delay times to resolve and reject the deferred object respectively

$(function () { function asyncEvent(){ var dfd = new jQuery.Deferred(); //Resolve after a random time interval setTimeout(function(){ dfd.resolve("Cheers"); }, Math.floor(400+Math.random()*2000)); //Reject after a random time interval setTimeout(function(){ dfd.reject("Sorry"); }, Math.floor(400+Math.random()*2000)); //Display a "working..." message every half second setTimeout(function working(){ if ( dfd.state() === "pending" ) { dfd.notify("working... "); setTimeout(working, 500); } }, 1); //Returns a Promise object; the caller cannot change the deferred object return dfd.promise(); } //Attach done, fail, and progress handlers to the asynchronous function $.when( asyncEvent() ).then( function(status){ alert( status+', things are going well' ); }, function(status){ alert( status+', this time you failed' ); }, function(status){ $("body").append(status); } ); })

Try it »

Definition and Usage

The deferred.promise() function returns the Promise object of a Deferred (delayed) object.

Note:1. This method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal requests.
2. It only contains a set of deferred object methods, including: done(), then(), fail(), isResolved(), isRejected(), always(). These methods can only observe the state of a deferred object, but cannot change the internal state of the deferred object.
3. deferred.promise() can also accept a target parameter. In this case, the passed-in target will be given the Promise methods and returned as the result, instead of creating a new object.


Syntax

deferred.promise( [target ] )

Parameters Description
target Object type: The object to which the promise methods are bound.


实例

More Examples

Using the target parameter
Using the target parameter to attach Promise methods to an existing object


jQuery 杂项方法jQuery Miscellaneous Methods

Other Extensions