This question may have been asked here before, and I'm sorry, but I wasn't able to find a solution to my problem anywhere. I am relatively new to JavaScript and things like "promises" are alien to me. I am trying to make a code that will load an array from a .JSON file, and after it loads, the code will continue.
async function fetchTags() {
var response = await fetch('../json/tags.json');
var json = await response.json();
console.log(json); // returns: Array()
return json;
}
function mainFunction() {
let tags = fetchTags();
console.log(tags); // returns: Promise { <state>: "pending" }
}
This is what my current code looks like, using a not-working "solution" I found on the internet. While the console.log(json)
, which is inside of the async function, returns the array correctly, the main function's console.log(tags)
displays this promise with a "pending" state - and displays sooner than the array can be loaded, if I understand correctly.
The following code of the mainFunction()
however relies strongly on this array, and it should not proceed before the array is loaded. Where am I making a mistake?
Thanks a lot for all your replies.