jQuery deferred.promise() method
Example
Set up two timers with random delays, used 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
(
"
Hooray
"
)
;
}
,
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
)
;
//
Return a Promise object so the caller cannot change the deferred object
return
dfd
.
promise
(
)
;
}
//
Attach a done, fail, and progress handler to an asynchronous function
$.
when
(
asyncEvent
(
)
)
.
then
(
function
(
status
)
{
alert
(
status
'
, things went 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 the Deferred.
**Note:** 1. The method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request.
2. Only a set of methods of the deferred object are included: 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 that case, the passed target will be assigned 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 promote an existing object's Promise
jQuery Miscellaneous Methods