如何在 jQuery 中的 $.when().then() 中使用 If 语句

k.e*_*rer 0 javascript jquery

我使用作为 JavaScript 控制器的初始化一个方法来获取参数。根据参数的值,我使用 $.when() 和 then() 方法从 ajax 调用中获取数据。

具体来说,如果传递的参数在 $.when 中为真,我想有 4 个 ajax 调用,否则有 3 个。

$.when(
    $.ajax({
        url: "test.html"
    }).done(function () {
        $(this).addClass("done");
    }),
    $.ajax({
        url: "test2.html"
    }).done(function () {
        $(this).addClass("done");
    }),
    $.ajax({
        url: "test3.html"
    }).done(function () {
        $(this).addClass("done");
    }),
    if (config,EditMode) {
        $.ajax({
            url: "test3.html"
        }).done(function () {
            $(this).addClass("done");
        })
    }
).then(function () {
    if (config,EditMode)
        somemethod();
    else
        someOtherMethod();
}).done(function () {
    //code
});
Run Code Online (Sandbox Code Playgroud)

我尝试了类似上面的方法,但我无法真正使语法起作用。当然,我可以创建一个全局 if else 并复制代码。但我会收到 DRY 原则的投诉:))。

你有什么想法吗?谢谢

Aln*_*tak 5

不要将您的$.ajax调用直接作为参数放在对 的调用中$.when()

一种更简单的方法是创建单个承诺的数组:

var promises = [];
promises.push($.ajax(...));
promises.push($.ajax(...));
promises.push($.ajax(...));
if (config.EditMode) {
    promises.push($.ajax(...));
}
Run Code Online (Sandbox Code Playgroud)

然后用于.apply传递列表:

$.when.apply($, promises).then(...);
Run Code Online (Sandbox Code Playgroud)

当您事先不知道要传递多少参数时,这是调用函数的常用方法。