then()
我一直在使用 fetch API 并从 由于它的状态管理,我能够用 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()
}
虽然我了解您希望为您的数据使用全局变量,但我建议不要污染全局命名空间(另请参阅:[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
参数的回调。
注意:如果/当您更改数据变量时请小心,您最终可能会多次更改它,并且由于丢失/格式不正确的数据而无意中导致错误。
祝你好运。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句