deferred.promise()
S2C Home « Objects « deferred.promise()
Deferred subset.
Description
The deferred.promise()
Deferred method provides a subset for a Deferred
object which prevents other code from interfering with the progress or status of its internal request..
- A Promise object provides the following subset of methods of the
Deferred
object:deferred.then()
,deferred.done()
,deferred.fail()
,deferred.always()
,deferred.pipe()
anddeferred.progress()
methods or determines the state through thedeferred.state()
method. - Ensure you keep a reference to the original
Deferred
object, so it can eventually be resolved or rejected.
Syntax
Signature | Description |
---|---|
deferred.promise( [target] ) | Return the promise object for a Deferred, optionally passing an object to attach the promise methods to. |
Parameters
Parameter | Description | Type |
---|---|---|
target | Object to attach the promise methods to. | Promise |
Return
A Promise
object.
deferred.promise( [target] )
ExamplesTop
Return the promise object for a Deferred, optionally passing an object to attach the promise methods to.
In the example below when we press the left button the first time we create a Deferred
object and a Promise
object from it. We then show
some methods that will and will not work on the Promise
object. We then notify and resolve the Deferred
object.
When we press the right button the first time we create a target object for our promise and a Deferred
object. We then set
the target object as our Promise
object. After this we resolve our Deferred
object, which will be be mirrored in the promise object and output some messages.
$(function(){
$('#btn26').one('click', function(){
var ourDeferred = $.Deferred(), ourPromise = ourDeferred.promise();
ourPromise.fail( bFunc ) // ok
ourPromise.done( bFunc ) // ok
ourPromise.progress( bFunc ) // ok
/*
* The following code would not work and produce an error. Cut and paste it
* and try in Firebug for instance
*
*/
// ourPromise.notify( 'Our promise was notified? <br>', '#div1' ) // NOT ok
// ourPromise.resolve( 'Our promise was resolved? <br>', '#div1' ) // NOT ok
ourDeferred.notify( 'Our deferred was notified? <br>', '#div1' )
ourDeferred.resolve( 'Our deferred was resolved? <br>', '#div1' )
});
$('#btn27').one('click', function(){
// Our target object for the Promise
var promiseTarget = {
msg: function( value, div ) {
$(div).append( value);
}
}, ourDeferred = $.Deferred();
// Set target object as a promise
ourDeferred.promise( promiseTarget );
ourDeferred.done( cFunc );
// Deferred is resolved and will be mirrored in the Promise
ourDeferred.resolve( 'Our deferred was resolved.<br>', '#div1' );
promiseTarget.done( function( value, div ) {
promiseTarget.msg( ' In Promise: ' + value +
' Our target promise is now "done"<br><br>' , div );
});
});
function cFunc( value, div ){
$(div).append( 'In cFunc: ' + value);
}
});
div1. Some initial text.