我担心你不得不求助于厄运金字塔(或回调金字塔):
first().then(function(firstResult) {
second(firstResult).then(function(secondResult) {
third(secondResult).then(function(thirdResult) {
// now you have all three results available in scope
});
});
});
如果你想把它弄平,我只能看到
var firstResult, secondResult, thirdResult;
$.when(first()).done(function(r) { firstResult = r; })
.then(second).done(function(r) { secondResult = r; })
.then(third).done(function(r) { thirdResult = r; })
.finally(function() {
// use the three results here
});
或某种
first().then(function(r) { return [r]; })
.then(function(a) {
return second(a[0]).then(function(r) { a.push(r); return a; });
}).then(function(a) {
return third(a[1]).then(function(r) { a.push(r); return a; });
}).finally(function(a) {
use a[0], a[1] and a[2] here
});
也许使用对象而不是数组的辅助函数arguments
可以简化:
function unfoldLast(fn) {
return function() {
var args = arguments,
l = args.length,
last = arguments[l-1];
return fn(last).then(function(r) {
var d = $.Deferred();
args[l] = r;
d.resolve.apply(d, args);
return d;
});
};
}
first().then(unfoldLast(second)).then(unfoldLast(third))
.done(function(firstResult, secondResult, thirdResult) {
// use the arguments!
});