You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery 1.11.2中$(document).ready内异步函数未被await问题

问题解决:$(document).ready中异步函数未正确等待的问题

你遇到的核心问题是:async函数本身返回Promise,自执行后变量存储的是Promise对象而非异步操作的结果,后续同步代码不会等待Promise完成,所以debugger和console.log看到的都是Promise,而非期望的JSON对象。

解决方案1:将$(document).ready回调改为async函数

直接把ready的回调函数声明为async,这样就能在内部使用await等待异步操作完成,后续代码会自然等待结果返回后再执行:

$(document).ready(async function () {
    try {
        var outcomeNameStrings = await getOutcomeNameStrings();
        console.log(outcomeNameStrings); // 现在是JSON对象
        // 所有依赖outcomeNameStrings的代码都放在这里
        debugger;
    } catch (err) {
        console.error('请求失败:', err);
    }
});

async function getOutcomeNameStrings() {
    return $.ajax({
        async: true,
        type: "GET",
        url: "/Outcomes/GetOutcomeNameStrings",
        dataType: "json"
    });
}

说明:

  • jQuery 1.11.2支持async函数作为ready回调,jQuery会正常执行它;
  • 加入try/catch可以捕获请求失败的异常,避免未处理错误导致后续代码中断;
  • $.ajax返回的Deferred对象与Promise兼容,所以可以直接用await等待。

解决方案2:使用.then回调包裹依赖代码

如果不想修改ready回调为async,可以将所有依赖异步结果的代码放在.then的回调函数内,确保只有当请求完成后才执行这些代码:

$(document).ready(function () {
    getOutcomeNameStrings().then(function(namesObj) {
        var outcomeNameStrings = namesObj;
        console.log(outcomeNameStrings); // JSON对象
        // 依赖outcomeNameStrings的代码放在这里
        debugger;
    }).fail(function(err) {
        console.error('请求失败:', err);
    });

    // 这里的代码会在请求完成前执行,不能使用outcomeNameStrings
});

async function getOutcomeNameStrings() {
    return $.ajax({
        async: true,
        type: "GET",
        url: "/Outcomes/GetOutcomeNameStrings",
        dataType: "json"
    });
}

说明:

  • 之前.then无效的原因大概率是你把依赖代码写在了.then外面,同步代码会先于.then回调执行,导致变量未被赋值;
  • 用.fail捕获请求失败的情况,和try/catch作用一致。

内容的提问来源于stack exchange,提问作者austinn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 09:45:28