jquery custom deferred functions

Brian picture Brian · Feb 22, 2013 · Viewed 14.5k times · Source

I have three functions i'm trying to run, the first two are doing some async stuff that need data for the third to use. I want the third function to fire only when 1 and 2 are both done. this is the general structure but the final function is firing before 1 and 2 finish.

function run() {
    var data1 = {};
    var data2 = {};

    $.when(first(), second()).done(constructData());

    function first() {
        var d = new $.Deferred();

        //do a bunch of stuff async
        data1 = {};

        d.resolve();
    }
    function second() {


        var d = new $.Deferred();

        //do a bunch of stuff async
        data2 = {};
        d.resolve();
    }
    function constructData() {
        //do stuff with data1 and data2
    }

}

Answer was to not call construct data immediately

 $.when(first(), second()).done(constructData);

Answer

dfsq picture dfsq · Feb 22, 2013

You should return promise object. You also have an error in this line:

$.when(first(), second()).done(constructData());

it should be

$.when(first(), second()).done(constructData); // don't call constructData immediately

So all together it could be:

function run() {
    var data1 = {};
    var data2 = {};

    $.when(first(), second()).done(constructData);

    function first() {
        return $.Deferred(function() { // <-- see returning Deferred object
            var self = this;

            setTimeout(function() {   // <-- example of some async operation
                data1 = {func: 'first', data: true};
                self.resolve();       // <-- call resolve method once async is done
            }, 2000);
        });
    }
    function second() {
        return $.Deferred(function() {
            var self = this;
            setTimeout(function() {
                data2 = {func: 'second', data: true};
                self.resolve();
            }, 3000);
        });
    }
    function constructData() {
        //do stuff with data1 and data2
        console.log(data1, data2);
    }
}

http://jsfiddle.net/FwXZC/