jQuery $.when(..).完成(..)未按预期工作

jQuery $.when(...).done(...) not working as desired

本文关键字:工作 完成 when jQuery      更新时间:2023-09-26

我有一个定时关键函数,在完成几次 Ajax 调用之前无法执行。Ajax 调用从服务器发出请求,以获取在初始页面加载时填充字段所需的数据。

我的 Ajax 调用正在工作,但它们在调用关键函数GetUserDefaults()之前没有完成。无论我在哪里设置断点(使用 Firefox),我都看到_MasterRules总是按预期初始化,但没有断点GetUserDefaults()在完成之前GetMasterRules()被调用。谁能告诉我document.ready中的代码出了什么问题?

这是我的代码示例:

_MasterRules = null;
_UserDefaults = null;
$(document).ready(function () {
    $.when( GetMasterRules() )
    .done(function () { 
        GetUserDefaults()  // <<== MUST NOT call until GetMasterRules() is complete
    });
})
// Initialize Master Rules
function GetMasterRules() {
    $.ajax({
        type: "GET",
        url: "/GetMasterRules",
        dataType: "json"
    })
    .done(function (data) {
        _MasterRules = data;
    })
}
// _MasterRules must be initialized before calling
function GetUserDefaults() {
    if (_MasterRules == null) {
        alert("_MasterRules == null");
    }
    $.ajax({
        type: "GET",
        url: "/GetUserDefaults",
        dataType: "json"
    })
    .done(function (data) {
        _UserDefaults = data;
    })
}

代码在将undefined传递给$.when时不会链接/等待延迟对象。

提示:GetMasterRules返回延迟。