繁体   English   中英

如何将 fetch API 请求中的 json 数据存储到全局变量中 - javascript

[英]How to store the json data from fetch API request into a global variable - javascript

我一直在使用 fetch API 并从then()成功地将数据记录到控制台,但我正在寻找一种方法将这些数据放入稍后将使用的全局变量中。 由于它的状态管理,我能够使用 reactjs 做到这一点,但在 vanilla javascript 中,由于返回的承诺很难做到

我尝试过的事情

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); })();

虽然我知道您希望为您的数据使用全局变量,但我建议不要污染全局命名空间(另请参见: [1][2][3][4] )。

您可以改为将所有内容封装在立即调用函数表达式 (IIFE)中,并在其中包含与程序该区域相关的所有代码的fetch方法。

然后,通过重新排列@alexanderdavide 的答案,我们得到以下代码:

(async () => {
  let data_local;

  const getData = async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
    const data = await response.json();
    dataGlobal = data;
    return data;
  };

  await getData();
  console.log(data_local);

  // your code goes here...
})();

您也可以使用以下替代方法:

(async () => {
  const getData = async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
    const data = await response.json();
    dataGlobal = data;
    return data;
  };

  let data_local = await getData();
  console.log(data_local);


  // your code goes here...
})();

这样,您的data_local变量将可供其下的所有内容使用,但不能在 IIFE 本身之外使用,从而保护全局命名空间,同时允许多个方法访问同一个变量,而无需使用带有data参数的回调。

注意:如果/当您更改数据变量时请小心,您最终可能会多次更改它,并且由于丢失/格式不正确的数据而无意中导致错误。

祝你好运。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM