我一直在使用 fetch API 并从 then()
成功将数据记录到控制台,但我正在寻找一种方法将此数据放入我将要使用的全局变量中稍后使用。我能够使用reactjs做到这一点,因为它的状态管理,但在普通的javascript中,由于返回的 promise ,这很难做到
我尝试过的事情
const res = await fetch('./data.json')
.then(res => res.json())
.then(data => data) // when I log from here I get the data but can't assign it to a global variable even tried using `var`
使用 async/await 仍然没有希望。
const fun = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
return response.json()
}
最佳答案
在获取远程数据的异步函数 getData
中,您可以将解析后的 JSON 正文作为 JavaScript 对象获取,并将其分配给全局中定义的变量 dataGlobal
上下文。
当然,在声明dataGlobal
之前,您必须等待getData
执行。因此,我使用异步 IIFE .
let dataGlobal;
const getData = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const data = await response.json();
dataGlobal = data;
return data;
};
(async () => {
await getData();
console.log(dataGlobal);
})();
关于javascript - 如何将 fetch API 请求中的 json 数据存储到全局变量中 - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72389096/