« Back to home

Using jQuery Deferred for long operations

The jQuery $.when() (part of the deferred object) function works great when using the AJAX function since it uses the deferred object by default.
What if you want to do something similar when performing asynchronous/synchronous operations by means of regular functions such as?

$.when(firstFunction(), secondFunction()).then(function() {
    console.log('Execute when all functions has completed');
});

Given the scenario above, what if you have a function that takes a little bit longer than the other function such as.

/** Create a long operation */
var loadQueue = function() {  
    var dfrQueue = new $.Deferred();
    var i = 0;
    var loop = window.setInterval(function() {
        ++i;
        console.log('queue 1 - running: '+i);
        if (i >= 10) {
            // pass optional param to success callback
           dfrQueue.resolve('queue 1');
           clearInterval(loop);
        }
     }, 1000);

     console.log('initialize test for queue 1');
     return dfrQueue.promise();
};
/** Create a second long operation */
var loadQueue2 = function() {  
    var dfrQueue = new $.Deferred();
    var i = 0;
    var loop = window.setInterval(function() {
        ++i;
        console.log('queue 2 - running: '+i);
        if (i >= 5) {
           // pass optional param to success callback
           dfrQueue.resolve('queue 2');
           clearInterval(loop);
        }
    }, 1000);

    console.log('initialize test for queue 2');
    return dfrQueue.promise();
};

To keep things simple, the loadQueue() and loadQueue2() both perform some things behind the scenes asynchronously based on some process (could be anything that
takes a long time to process). The setInterval() function is used to simulate a process that takes 5 and 10 seconds which the loadQueue being the last one to
finish. In the end, both functions can be called and a callback function can be called when both functions has succeeded.

/** Using $.when() for 2 asynchronous or long running operations 
but additional functions can be added as long as they all return  
a promise object. */  
$.when(
    loadQueue(), loadQueue2())
.then(function(arg) {
// all operations has completed and console out the argument provided by the last operation that completed.
    console.log('all process succeeded: ' + arg);
});

This is based on an assumption that a callback is called once and after all functions has successfully completed.

The complete code can be found here. Gist

Comments

comments powered by Disqus