问题
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
回答1:
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/
回答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));
来源:https://stackoverflow.com/questions/33060171/combine-multiple-jquery-deferred-objects-into-a-new-deferred-object