Understanding your preference for a global variable to store data, I would caution against overpopulating the global namespace (refer also: [1], [2], [3], and [4]).
An alternative approach would be to encapsulate everything within an Immediately Invoked Function Expression (IIFE) where your fetch
method resides along with all related code.
Reorganizing the solution provided by @alexanderdavide, we arrive at the following snippet:
(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);
// insert your code here...
})();
You may also consider this variation:
(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);
// insert your code here...
})();
This way, the data_local
variable remains accessible within the scope of the IIFE but not externally, safeguarding the global namespace while enabling multiple methods to access the same variable without relying on callbacks with a data
parameter.
NOTE: Exercise caution when modifying the data variable as multiple alterations could lead to errors due to missing or improperly formatted data.
Best of luck.