Aaron Shen
Aaron Shen

Reputation: 8374

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

Upvotes: 3

Views: 2259

Answers (2)

dpr
dpr

Reputation: 10964

Rather old question but it took me some time to find an answer for a dynamic number of deffereds/promises that are to be combined:

const promises = [];
promises.push($.Deferred());
...
promises.push($.Deferred());
// execute $.when using Function.apply to pass the array of promises as arg
$.when.apply(null, promises).done(function() {
  // executed after all promises are "done"
});

In the context of the OP's question:

aaa.then(function() { return $.when.apply(null, [bbb(), ccc()] }).done(ddd));

Upvotes: 2

jfriend00
jfriend00

Reputation: 707496

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/

Upvotes: 3

Related Questions