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

JavaScript中使用Fetch API获取数据供Plotly绘图的异步问题求助

问题核心原因

fetch 是异步API,发起请求后不会阻塞后续代码执行,你在fetch作用域外访问sugars、times的时候,请求还没完成,数组还没被赋值,自然会拿到空值或者undefined。

解决方案1:直接在.then回调中执行绘图逻辑

你只需要把Plotly的绘图代码移到第二个.then回调里即可,数据拿到后直接执行绘图,不需要往外层传数据:

// fetch the BG data from the API and write results into arrays
fetch(url)
    .then((resp) => resp.json())
    .then((result) => {
        const sugars = [];
        const times = [];
        // 处理数据
        for (let i = 0; i < n_entries; i++) {
            sugars[i] = result[i]["sgv"];
            times[i]  = -i * timestep;
        }
        // 直接在这里执行Plotly绘图
        const trace = {
            x: times,
            y: sugars,
            type: 'scatter'
        };
        const data = [trace];
        Plotly.newPlot('你的绘图容器DOM ID', data);
    });

解决方案2:用async/await封装逻辑,代码结构更直观

如果不想把所有逻辑都塞到.then里,可以用async/await的写法简化异步流程:

// 封装数据拉取逻辑
async function getGlucoseData() {
    const resp = await fetch(url);
    const result = await resp.json();
    const sugars = [];
    const times = [];
    for (let i = 0; i < n_entries; i++) {
        sugars[i] = result[i]["sgv"];
        times[i]  = -i * timestep;
    }
    // 返回处理好的数据
    return { sugars, times };
}

// 调用函数拉取数据后绘图
async function renderPlot() {
    const { sugars, times } = await getGlucoseData();
    const trace = {
        x: times,
        y: sugars,
        type: 'scatter'
    };
    const data = [trace];
    Plotly.newPlot('你的绘图容器DOM ID', data);
}

// 执行绘图
renderPlot();

注意事项

  • 把代码里的你的绘图容器DOM ID替换为你页面上用来放置Plotly图表的DOM元素的id,比如HTML里写了<div id="bg-plot"></div>,这里就填'bg-plot'
  • 所有依赖请求返回数据的逻辑,都必须放在异步回调里,或者在await之后执行,不能在异步操作还未完成时访问对应数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:54:03