it:ad:promise:howto:waiting_for_several_operations_before_continuing

IT:AD:Promise:HowTo:Waiting for several operations before continuing

Use the $.when() (notice the $. prefix).

And combine it either with:

  • done(successfulResult)

    or

  • then(successfulResult,failedResult)

Below is an example of using done.

$(function(){
    DemoC();
});


function DemoC(){
    $
    .when(FirstLongProcess(5), SecondLongProcess(10))
    .then(ProcessBothSuccess,ProcessBothFailed);
}

function ProcessBothSuccess(d1, d2){$("#r").html("Success: "+d1+":"+d2);}
//Important: Notice how fail just has arg of the failed one. Not both.
function ProcessBothFailed(d1, d2){$("#r").html("Fail: "+d1+":"+d2);}


function FirstLongProcess(data){
    //setup a deferred object:
    var deferred = $.Deferred();
    
    // Take a second, then invoke a callback:
    window.setTimeout(
        function() {
            var x= Math.round(Math.random())==1;
            //x=true;
            if (x){
                //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();
}


function SecondLongProcess(data){
    //setup a deferred object:
    var deferred = $.Deferred();
    
    // Take a second, then invoke a callback:
    window.setTimeout(
        function() {
            var x= Math.round(Math.random())==1;
            //x=true;
            if (x){
                //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();
}

  • /home/skysigal/public_html/data/pages/it/ad/promise/howto/waiting_for_several_operations_before_continuing.txt
  • Last modified: 2023/11/04 01:54
  • by 127.0.0.1