IT:AD:Promise:HowTo:Chaining Async Promises Together
Summary
We just saw how to chain one or more then() statements to handle the async response of promises.
But you can also chain together one or more async operations.
Process
One example of chaining async calls together is presented below:
$(function(){
DemoC();
});
function DemoC(){
FirstLongProcess(5).then(DoSuccess, DoFail);
}
function DoSuccess(data){$("#r").html("Success: "+data);}
function DoFail(data){$("#r").html("Fail: "+data);}
function FirstLongProcess(data){
//setup a deferred object:
var deferred = $.Deferred();
// Take a second, then invoke a callback:
window.setTimeout(
function() {
if (Math.round(Math.random())==1){
//Call second long running method,
//waiting for its return before continuing
SecondLongProcess(data+10)
.then(
function(data){
//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() {
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();
}