IT:AD:Promise:HowTo:Waiting for several operations before continuing
Summary
Sometimes you don't want to chain things but want to process things in parrallel, but wait for them both to complete before continuing.
Process
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();
}