Easy Tutorial
❮ Misc Deferred Pipe Jquery Plugin Accordion ❯

jQuery deferred.promise() Method

jQuery Miscellaneous Methods

Example

Set up two timers with random delay times, one to resolve and one to reject the deferred object.

$(function () { 
    function asyncEvent(){
        var dfd = new jQuery.Deferred();
        // Resolve after a random interval
        setTimeout(function(){
            dfd.resolve("Hooray");
        }, Math.floor(400 + Math.random() * 2000));
        // Reject after a random 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 the Promise object, preventing the caller from changing 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 + ', you failed this time' );
        },
        function(status){
            $("body").append(status);
        }
    );
})

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 its internal request's progress or status.


Syntax

Parameter Description
target Object type, the object to which the promise methods are bound.

More Examples

Using the target parameter


jQuery Miscellaneous Methods

❮ Misc Deferred Pipe Jquery Plugin Accordion ❯