<button id="click">Click Me</button>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var async1 = function(){
console.log('async1')
var dfd = new $.Deferred();
setTimeout(function(){
console.log('async1 resolved!')
dfd.resolve();
}, 5000);
return dfd.promise();
};
var async2 = function(){
console.log('async2')
var dfd = new $.Deferred();
setTimeout(function(){
console.log('async2 rejected')
dfd.reject();
}, 5000);
return dfd.promise();
};
var async3 = function(){
console.log('async3')
var dfd = new $.Deferred();
setTimeout(function(){
console.log('async3 resolved!')
dfd.resolve();
}, 5000);
return dfd.promise();
};
$('#click').on('click', function(){
async1()
.then(async2) //only fires if async1 resolves
.then(async3 /*only fires if async2 resolves*/, function(){
console.log('don\'t run 3 because 2 got rejected')//fires if anyone up the chain rejects
}).done(function(){ //only fires if the entire chain succeeds
console.log('done fired!')
}).fail(function(){ //only fires if someone in the chain rejects (every 'then' will continue to cascade, but will hit fail callbacks since subsequent 'thens' can't resolve )
console.log('fail fired')
}).always(function(){ //always fires
console.log('always fired')
})
});
});
</script>
Saturday, October 26, 2013
Firing Async Functions in order with $.Deferred
I have been spending quite a bit of time with deferreds and promises in Javascript, and just wanted to share what I have learned with chaining functions sequentially using JQuery's Deferred:
Subscribe to:
Posts (Atom)