JQuery 函数 returns 承诺但 'when' 仍然不等待

JQuery function returns promise but 'when' still doesn't wait

我刚刚了解到 $.when().then() 功能。我一直在努力让它发挥作用,我看过很多例子,但我显然还没有完全理解,因为我无法让它发挥作用。我知道无论我将什么函数作为参数传递给 when() 函数,都必须 return 一个 promise 对象。我觉得我所做的应该可行,但还不是很清楚,我仍然不理解某些东西。在我下面的代码中,loadUserInterfaceGroupsDropDown()initializeUserInterfaceGroups() 中的 ajax 调用完成之前执行。请注意,我 return ajax 调用的结果。这应该产生与我看到的将 ajax 调用作为参数传递给 when() 语句的许多简单示例相同的结果。另外,我 return 在底部的 else 语句中承诺。但是由于这似乎不起作用,所以我显然误解了一些东西。请帮忙。

$.when(initializeUserInterfaceGroups()).then(loadUserInterfaceGroupsDropDown());

function initializeUserInterfaceGroups() {
    if (userInterfaceGroups === undefined) {
        // get the UserInterfaceGroups
        return $.ajax({
            type: "POST",
            url: "Users.aspx/GetUserInterfaceGroups",
            data: "{organizationId: " + $("#ddOrganization").val() + "}",
            datatype: "json",
            contentType: "application/json; charset=utf-8",
            success: function(response) {
                if (response.d.Success) {
                   userInterfaceGroups = response.d.UserInterfaceGroups;
                   //loadUserInterfaceGroupsDropDown();
                    renderCheckboxLists();
                } else {
                   alert(response.d.ErrorMessage);
                }
            },
            failure: function(response) {
               alert('Error getting the UserInterfaceGroups: ' + response.d);
            }
        });
    } else {
        return $.Deferred().promise();
    }
}

.when().then() promise 与多个 ajax 函数一起使用的正确语法如下所示:

$.when($.ajax(...), $.ajax(...)).then(function (resp1, resp2) {
    //this callback will be fired once all ajax calls have finished.
});

所以基本上你需要像上面那样改变你的调用方法。希望对您有所帮助!

this doesn't seem to be working - I've obviously misunderstood something.

$.when(initializeUserInterfaceGroups()).then(loadUserInterfaceGroupsDropDown());

是的,两件事:

  • 当你已经有了承诺时,你绝对不需要 $.when。只有当您不确定调用的 return 值是否是一个承诺时,或者当您有多个承诺要等待时,才应该使用它。这里也不是这样。
  • then 需要一个 回调函数 。您不能立即调用 loadUserInterfaceGroupsDropDown()(这就是它不等待的原因)并将结果传递给 then,您必须传递函数本身。 (或者至少将调用包装在函数表达式中)。

所以你的代码应该是

initializeUserInterfaceGroups().then(loadUserInterfaceGroupsDropDown);

我想我会更新我所做的。我仍在学习有关如何最好地使用它的新知识。最后它仍然是我需要的完美答案,但我确实需要改变一些东西。有人指出,我在我的 ajax 调用之一的 else 语句中返回了一个未解决的承诺。 虽然这似乎暂时对我有用,但我需要进一步研究。这是我的工作代码,希望它能帮助别人。我这样做是因为即使在得到正确答案之后,我仍然需要弄清楚一些事情,所以希望这会对某人有所帮助:

$.when(getUserInterfaceGroups(), getUserDetail($(this).attr("data-userId"))).done(function(resp1, resp2) {
    renderUserInterfaceGroupControls(resp1[0], resp2[0]);
    populateForm(resp2[0]);
});

function getUserInterfaceGroups() {
    if (userInterfaceGroups === undefined) {
        return $.ajax({
            type: "POST",
            url: "Users.aspx/GetUserInterfaceGroups",
            data: "{organizationId: " + $("#ddOrganization").val() + "}",
            datatype: "json",
            contentType: "application/json; charset=utf-8",
            failure: function(response) {
                alert('Error getting the UserInterfaceGroups: ' + response.d);
            }
        });
    } else {
        return $.Deferred().promise();
    }
}

function getUserDetail(userId) {
    return $.ajax({
        type: "POST",
        url: "Users.aspx/GetUser",
        data: "{userId: " + userId + "}",
        datatype: "json",
        contentType: "application/json; charset=utf-8",
        failure: function (response) {
            alert('Error getting the User details: ' + response.d);
        }
    });
}

function renderUserInterfaceGroupControls(resp1, resp2) {
    if (resp1.d.Success && resp2.d.Success) {
        userInterfaceGroups = resp1.d.UserInterfaceGroups;
        loadUserInterfaceGroupsDropDown(resp2.d.UserDetail.InterfaceModeId);
        renderCheckboxLists();
    } else {
        alert(response.d.ErrorMessage);
    }
}

function populateForm(response) {
    if (response.d.Success) {
        var userDetails = response.d.UserDetail;
        $("#txtUserCode").val(userDetails.UserCode);
        $("#txtName").val(userDetails.Name);
        $("#txtPassCode").val(userDetails.PassCode);
        $("#ddUserInterfaceGroup option[value='" + userDetails.UserInterfaceGroupId + "']").prop("selected", true);
        $("#txtEmail").val(userDetails.Email);
        $("#dtBirthDate").val(userDetails.DateOfBirth);
        $.each(userDetails.ContactGroupIds, function (idx) {
            $("div input[type=checkbox][value=" + userDetails.ContactGroupIds[idx] + "]").prop('checked', true);
        });
        if (userDetails.AssetTagNumber === "") {
            $("#rbUserOwned").prop("checked", "checked");
        } else {
            $("#txtAssetTag").val(userDetails.AssetTagNumber);
        }
        $("#hidUserId").val(userDetails.Id);
        showInputFields();
    } else {
        alert(response.d.ErrorMessage);
    }
}