Demo of JQuery Promises

by Sky Sigal

HTML

<span id="r"/>

JavaScript

$(function(){
    //DemoA();
    //DemoB();
    DemoC();
});

function DemoA(){
    //Invoke the method passing callbacks:
    SimulateSomethingThatTakesTime(
        5,
        function(data){$("#r").html("Success: "+data);},
        function(data){$("#r").html("Fail: "+data);}
        );
}

function SimulateSomethingThatTakesTime(data, onSuccessCallback, onErrorCallback){
    // Take a second, then continue:
    window.setTimeout(
        function() {
            //simulate randomly successful/failed results
            //modifying original data differently:
            if (Math.round(Math.random())==1){
                if (onSuccessCallback){onSuccessCallback(data+1);}
            }else{
                if (onErrorCallback){onErrorCallback(data-1);}
            }
        },1000);
}


function DemoB(){
    SimulationUsingPromises(5)
    .then(
        //Success callback is first arg:
        function(data){$("#r").html("Success: "+data);},
        //Success callback is second arg:
        function(data){$("#r").html("Fail: "+data);}
         );
}

function DoSuccess(data){$("#r").html("Success: "+data);}
//Success callback is second arg:
function DoFail(data){$("#r").html("Fail: "+data);}

function DemoC(){
    //same as DemoB, but cleaner with implicit passing of args:
    SimulationUsingPromises(5).then(DoSuccess, DoFail);
}


function SimulationUsingPromises(data){
    //setup a deferred object:
    var deferred = $.Deferred();
    
    // Take a second, then invoke a callback:
    window.setTimeout(
        function() {
            if (Math.round(Math.random())==1){
                //invoke resolve, passing results:
                deferred.resolve(data+1);
            }else{
                //invoke reject, passing results:
                deferred.reject(data-1);
            }
        },1000);
    //important: pass back the promise handle:
    return deferred.promise();
}