将延迟数组传递给 $.when()

这是一个人为的例子:http://jsfiddle.net/adamjford/YNGcm/20/

HTML:

<a href="#">Click me!</a>
<div></div>

JavaScript:

JavaScript:

function getSomeDeferredStuff() {
    var deferreds = [];

    var i = 1;
    for (i = 1; i <= 10; i++) {
        var count = i;

        deferreds.push(
        $.post('/echo/html/', {
            html: "<p>Task #" + count + " complete.",
            delay: count
        }).success(function(data) {
            $("div").append(data);
        }));
    }

    return deferreds;
}

$(function() {
    $("a").click(function() {
        var deferreds = getSomeDeferredStuff();

        $.when(deferreds).done(function() {
            $("div").append("<p>All done!</p>");
        });
    });
});

我想要全部完成!"在所有延迟任务完成后出现,但 $.when() 似乎不知道如何处理延迟对象数组.全做完了!"首先发生是因为数组不是 Deferred 对象,所以 jQuery 继续并假设它刚刚完成.

I want "All done!" to appear after all of the deferred tasks have completed, but $.when() doesn't appear to know how to handle an array of Deferred objects. "All done!" is happening first because the array is not a Deferred object, so jQuery goes ahead and assumes it's just done.

我知道可以将对象传递给像 $.when(deferred1, deferred2, ..., deferredX) 这样的函数,但不知道实际执行时会有多少 Deferred 对象我正在尝试解决的问题.

I know one could pass the objects into the function like $.when(deferred1, deferred2, ..., deferredX) but it's unknown how many Deferred objects there will be at execution in the actual problem I'm trying to solve.

推荐答案

要将一组值传递给 any 通常期望它们是单独参数的函数,请使用 Function.prototype.应用,所以在这种情况下你需要:

To pass an array of values to any function that normally expects them to be separate parameters, use Function.prototype.apply, so in this case you need:

$.when.apply($, my_array).then( ___ );

参见http://jsfiddle.net/YNGcm/21/

在 ES6 中,您可以使用 ... 传播运算符 代替:

In ES6, you can use the ... spread operator instead:

$.when(...my_array).then( ___ );

在任何一种情况下,由于您不太可能事先知道 .then 处理程序需要多少形式参数,因此该处理程序需要处理 arguments数组以检索每个承诺的结果.

In either case, since it's unlikely that you'll known in advance how many formal parameters the .then handler will require, that handler would need to process the arguments array in order to retrieve the result of each promise.

相关文章