Manage async events with Jquery promise
Do something when all a,b,c,d asynchronous tasks are completed.
The first task
function doFirstTask(){
var d = $.Deferred();
setTimeout(function(){
console.log("im done");
d.resolve();
}, 2000);
return d;
}
Now the second task
function doSecondTask(){
setTimeout(function(){
console.log("im done too");
d.resolve();
}, 2000);
return d;
}
Final task
function doThirdTask(){
setTimeout(function(){
console.log("all done");
d.resolve();
}, 2000);
return d;
}
The Magic chaining
doFirstTask().then(doSecondTask).then(doThirdTask);
Bonus!
All Jquery Ajax calls return a promise(deferred) object
// wait for multiple sets to finish
var r = $.ajax(),
m = $.ajax();
$.when( r, m ).done(function() {
// do something
});
Written by Sachin Saluja
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Jquery
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#