-2

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.

ongn
  • 1
  • 2
  • 2

1 Answers1

2

At this point, fetchTags is an asynchronous function and needs to be treated as such when calling it. You have two implementation options here:

  1. Use async/await for your mainFunction function:
async function mainFunction() {
    let tags = await fetchTags()
    console.log(tags)
}
  1. Appropriately handle the promise that is returned by the function:
function mainFunction() {
    fetchTags()
      .then(console.log)
      .catch(console.error)
}
m_callens
  • 6,100
  • 8
  • 32
  • 54
  • The `mainFunction` has around 80 more lines of code. After I turned the `mainFunction` to async, it misbehaved and threw errors like crazy. I don't know how I can fit the code in a `.then` as well... – ongn Jun 05 '21 at 01:41
  • @ongn there's nothing inherently different about the function when you add `async/await` to it. Its likely those errors were there before and weren't being logged? Can't give much guidance without seeing the errors or the rest of the function. – m_callens Jun 07 '21 at 01:03