While I understand that you'd like a global variable for your data, I would advise against polluting the global namespace (see also: [1], [2], [3] and [4]).
You could instead encapsulate everything in an Immediately Invoked Function Expression (IIFE), and have your fetch
method inside of it with all of the code related to that area of your program.
Then, by rearranging @alexanderdavide's answer, we get the following code:
(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...
})();
You could also use the following alternative as well:
(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...
})();
That way your data_local
variable would be available to everything beneath it but not outside of the IIFE itself, protecting the global namespace while allowing multiple methods access to the same variable without using callbacks with a data
argument.
NOTE: please be careful if/when you change the data variable, you might end up changing it multiple times and inadvertently causing an error because of missing / improperly formatted data.
Good luck.