将一组延迟传递给 $.when() [英] Pass in an array of Deferreds to $.when()

查看:24
本文介绍了将一组延迟传递给 $.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.

推荐答案

要将一组值传递给任何函数,这些函数通常希望它们是单独的参数,请使用 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.

这篇关于将一组延迟传递给 $.when()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆