如何从 API 获取结果以存储为全局变量?
How do I get fetch result from API to store as a global variable?
我正在做一个项目,我提取美国 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)
目前,我可以在第二个函数中使用 console.log(json) 和 console.log(jsondata)。然而,即使我已经在函数外部声明了变量,它并没有使变量成为它自己的全局变量。我错过了什么?
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();
我正在做一个项目,我提取美国 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)
目前,我可以在第二个函数中使用 console.log(json) 和 console.log(jsondata)。然而,即使我已经在函数外部声明了变量,它并没有使变量成为它自己的全局变量。我错过了什么?
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();