【发布时间】:2017-10-17 07:52:31
【问题描述】:
我刚刚了解了$.when().then() 功能。我一直在努力让它发挥作用,我已经看过很多例子,但我显然还没有完全理解,因为我无法让它发挥作用。我知道我作为参数传递给when() 函数的任何函数都必须返回一个promise 对象。我觉得我所做的应该有效,但它并没有那么清楚,我仍然不理解某些东西。在我下面的代码中,loadUserInterfaceGroupsDropDown() 在 initializeUserInterfaceGroups() 内部的 ajax 调用完成之前执行。请注意,我返回了 ajax 调用的结果。这应该会产生与我看到的许多将 ajax 调用作为参数传递给 when() 语句的简单示例相同的结果。我还在底部的 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();
}
}
【问题讨论】:
-
$.Deferred().promise();返回一个永远不会解决的承诺。我不认为那是你想要的。