0

想象一下,我正在链接三个异步调用,如下所示:

$.when(first()).then(second()).then(third())

first(), second(), 并且third()都返回 Deferred 对象。

在链的末端,我想收集所有已解决的问题。在我的脑海中,我想象:

$.when(first()).then(second()).then(third()).finally(
  function(first,second,third){
    //Do stuff with the three returns here
  }
);

但是有做这样的事情的语法吗?或者怎么做?

或者,换一种说法,这样的语法可以确保, 和$.when(first(),second(),third())的顺序、非重叠执行first(),这将是理想的。second()third()

4

1 回答 1

0

我担心你不得不求助于厄运金字塔(或回调金字塔):

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!
 });
于 2013-08-03T16:31:36.633 回答