deferred.promise() JQ 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..


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
targetObject to attach the promise methods to.Object

Return

A Promise object which is just a copy of a Deferred object without any notify/resolve/reject methods.


deferred.promise( [target] ) ExamplesObjects  <<  Top

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.

Press the button below to action the above code:

                

Related Tutorials

jQuery Advanced Tutorials - Lesson 7 - The Deferred Object