1

I want to read a json file but when I use await it seems to not wait for the file to get into the var

I have this code:

var webshopItems;
window.addEventListener('load', Initieer);

function Initieer() {
      ReadJSON();
      console.log(webshopItems[0].Name)
};

const ReadJSON = () => {
  let path = 'js/webshopItems.json';
  (async () => {
        webshopItems = await(GetJSON(path));
  })()
}

const GetJSON = async (file) => {
    let response = await fetch(file);
    let data = await response.json();
    return data;
}

So when I try this code webshopItems is undefined when i try to get the name. The name is correct because if i debug at somepoint it will get loaded just not in time.

1 Answer 1

1

It's not working because you're not waiting for the response.

var webshopItems;
window.addEventListener('load', Initieer);

async function Initieer() {
      await ReadJSON();
      console.log(webshopItems[0].Name)
};

const ReadJSON = async () => {
  let path = 'js/webshopItems.json';
  webshopItems = await(GetJSON(path));
}

const GetJSON = async (file) => {
    let response = await fetch(file);
    let data = await response.json();
    return data;
}
Sign up to request clarification or add additional context in comments.

1 Comment

just for clarification because i didnt see it the first time: ReadJSON the inner async is removed and readjson() is now an async

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.