gpt4 book ai didi

javascript - 将 $.when() 与可变函数数组一起使用

转载 作者:行者123 更新时间:2023-11-30 17:39:40 25 4
gpt4 key购买 nike

我想使用 when() 来控制多个 AJAX 调用的完成,例如:

$.when(
$.ajax( "test.aspx" ),
$.ajax( "test2.aspx" ),
...
).then(...);

最后,我想将 $.when 用于来自变量数组的函数调用结果。我不知道怎么做。

我们如何纠正下一个构造?这个问题是不正确的,因为我们传递了一个函数对象数组,而不是函数调用的结果。

funcArray = [ 
function() { return $.ajax( "test.aspx" ) },
function() { return $.ajax( "test2.aspx" ) }
]

if( cond )
{
funcArray.push( function() { return $.ajax( "test3.aspx" ) } )
}

$.when.apply( null, funcArray ).then(...); // how to correct here and probably somewhere else?

最佳答案

正如 Mattias Buelens 在 a comment 中所说的那样,问题在于您将返回 promise 的函数传递给 $.when – 而不是实际的 promise 。

您必须迭代数组并返回每个函数调用的结果。

有几种方法可以这样做:

  • [最稳定] 使用 jQuery 的 $.map功能:

    $.when.apply(null, $.map(funcArray, function (val) {
    return val();
    })
    );
  • 使用 Array.prototype.map() :

    $.when.apply(null, funcArray.map(function (val) {
    return val();
    })
    );
  • Firefox ≥ 22 还允许使用所谓的语法 arrow functions :

    $.when.apply(null, funcArray.map(fun => fun()));

关于javascript - 将 $.when() 与可变函数数组一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21353131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com