Search code examples
jqueryjquery-deferred

Combine multiple jQuery Deferred objects into a new Deferred object


here's the code: http://jsbin.com/lizami/edit?js,console

Paste the code here as well:

var aaa = $.Deferred();

var bbb = function(data){

    console.log(data);

    var dfd = $.Deferred();
    setTimeout(function(){
        dfd.resolve("bbb is done");
    }, 1000);
    return dfd.promise();
};

var ccc = function(data){
    console.log(data);

    var dfd = $.Deferred();
    setTimeout(function(){
        dfd.resolve("ccc is done");
    }, 1000);
    return dfd.promise();
};

var ddd = function(data){
    console.log(data);

    return data;
};



aaa.then([bbb,ccc]).then(ddd);
aaa.resolve("aaa is done");

What I want is to start two new deferred: bbb and ccc when aaa is resolved. And when both bbb and ccc are resolved. call ddd with the resolved data of bbb and ccc.

Is it possible? The jsbin doesn't work


Solution

  • In jQuery, you can use $.when() to combine multiple promises into one.

    aaa.then(function() {
        return $.when(bbb(), ccc());
    }).then(ddd);
    

    This will wait for aaa to resolve, then it will run both bbb() and ccc() and when they both resolve, it will then call ddd().

    Working demo: http://jsfiddle.net/jfriend00/2f7btsq7/