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

标签 javascript jquery

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

具体来说,$ 中传递的参数是否为 true。当我想要 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
});

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

你有什么想法吗? 谢谢

最佳答案

请勿将 $.ajax 调用直接作为参数调用 $.when()

更简单的方法是创建一个包含各个 Promise 的数组:

var promises = [];
promises.push($.ajax(...));
promises.push($.ajax(...));
promises.push($.ajax(...));
if (config.EditMode) {
    promises.push($.ajax(...));
}

然后使用.apply传递列表:

$.when.apply($, promises).then(...);

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

关于javascript - 如何在 jQuery 中的 $.when().then() 中使用 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49531089/

相关文章:

javascript - '_link' 与 '_trackEvent' 冲突

javascript - 在 meteor 项目中集成 Chessboard.js

javascript - 自动完成 : how to pass an extra parameter to the response callback

javascript - 7 位和 16 位的 jquery SMS 字符计算器

jquery - 如何让这个 jQueryUI 按钮与使用自定义 CSS 样式创建的按钮大小相同?

javascript - VueJS 资源重新加载内容

javascript - 使用 jQuery/JS 打开时,使 <details> 标签的内容具有动画效果

jquery - IE10 从 URL 中删除主题标签

javascript - 单击另一个 <a> 时给出 "selected"类,然后如果它是相同的 <a> 则删除该类

jquery - 仅在折叠时将 jQuery-UI sortable() 应用于 Accordion() 元素