3

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

0

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.