jQuery Chain&搜集

时间:2013-08-03 16:21:25

标签: jquery promise chaining

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

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

first()second()third()都返回延期对象。

在链的最后,我想收集已解决的所有内容。在我看来,我想:

$.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()的顺序,非重叠执行是理想的。

1 个答案:

答案 0 :(得分: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!
 });