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

如何让脚本等待await fetch执行完成后再继续运行?

解决fetch请求未等待完成就执行后续代码的问题

问题根源

  1. record是异步函数,直接调用let outcome = record(...)得到的是Promise对象,不是请求返回的实际结果,原代码里直接访问result.outcome不仅拿不到数据,还会因为result未定义报错。
  2. 你尝试的then方法没生效,大概率是因为没把创建的<p>元素添加到页面的record_creation容器里,结果虽然渲染了但看不到。

修复方案

方案一:用async/await包裹调用逻辑

把调用异步函数的代码放到async函数里,通过await等待请求结果:

async function record(recording_url, options) {
    const recording_outcome = await fetch(recording_url, options);
    const outcome = await recording_outcome.json();
    return outcome;
}

// 用async函数包裹调用逻辑
async function handleRecord() {
    let record_div = document.getElementById("record_creation");
    let record_saved = document.createElement("p");
    
    try {
        // 等待异步请求完成拿到结果
        const result = await record(recording_url, options);
        record_saved.innerText = result.outcome;
        // 把元素添加到页面容器
        record_div.appendChild(record_saved);
    } catch (err) {
        // 处理请求失败的情况
        record_saved.innerText = "请求失败:" + err.message;
        record_div.appendChild(record_saved);
    }
}

// 执行函数
handleRecord();

方案二:正确使用then方法(并添加元素到DOM)

在then回调里设置文本后,必须把元素添加到页面容器,同时添加错误处理:

async function record(recording_url, options) {
    const recording_outcome = await fetch(recording_url, options);
    const outcome = await recording_outcome.json();
    return outcome;
}

let outcome = record(recording_url, options);
let record_div = document.getElementById("record_creation");
let record_saved = document.createElement("p");

outcome.then(function(result){
   record_saved.innerText = result.outcome;
   // 必须把元素添加到容器才能在页面显示
   record_div.appendChild(record_saved);
}).catch(function(err){
    // 处理请求异常
    record_saved.innerText = "请求失败:" + err.message;
    record_div.appendChild(record_saved);
});

关键注意点

  • 异步函数的返回值永远是Promise,必须用await或者.then()来获取实际结果。
  • 动态创建的DOM元素,必须调用appendChild或类似方法添加到页面已存在的容器中,才能在浏览器里显示。
  • 一定要添加错误处理(try/catch或.catch()),避免请求失败时脚本崩溃。

内容的提问来源于stack exchange,提问作者Jcarty-Pinner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 09:57:16