如何从 API 获取结果并将其存储为全局变量?

Dav*_*eke 9 javascript scope fetch-api

我正在开发一个项目,在该项目中,我提取美国 GDP 的 API,然后根据数据创建图表。现在,我对问题的第一部分感到困惑,因为我正在努力将 JSON 存储在变量中,以便我可以在项目的其余部分中使用它。我查看了其他一些线程,但没有找到适合我的解决方案。

下面是我当前的代码。

let jsondata =;

fetch('https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json').then(
    function(u){ return u.json();}
  ).then(
    function(json){
        jsondata = json;
        console.log(jsondata)
    }
  )


console.log(jsondata)
Run Code Online (Sandbox Code Playgroud)

目前,我可以在第二个函数中使用 console.log(json) 和 console.log(jsondata) 。但是,即使我在函数外部声明了该变量,它也不会使该变量成为自身全局变量。我缺少什么?

ToT*_*Max 16

fetch是一个异步函数。这意味着当调用该函数时,它会被添加到事件循环中并且代码将继续。当它到达最后一行时,jsondata变量将尚未被填充,因为fetch函数尚未完成。

您应该await在函数前面添加一个函数,以确保它在代码继续之前完成。例如,请参阅:https ://dev.to/shoupn/javascript-fetch-api-and-using-asyncawait-47mp

let jsondata = "";
let apiUrl = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json"

async function getJson(url) {
    let response = await fetch(url);
    let data = await response.json()
    return data;
}

async function main() {
    //OPTION 1
    getJson(apiUrl)
        .then(data => console.log(data));

    //OPTION 2
    jsondata = await getJson(apiUrl)
    console.log(jsondata);
}

main();
Run Code Online (Sandbox Code Playgroud)