Last Updated: February 25, 2016
·
1.067K
· jsrockstar

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
});