3

I have two files that are arrays, and i want to load them from a fetch. I have an async function that fetch the files:

async function getData(file) {
    const data = await fetch(`./assets/resources/${file}.json`);
    return await data.json()
}

Then here is where i assign the variables to the return fo this fetch:

let notes = getData("notes").then(res => res)
let pentagrama = getData("pentagrama").then(res => res)

But with this all i get is: from google chrome console

How can i actually get the value?

2
  • You may have a look at how to return the response from an asynchronous call? Commented Dec 23, 2017 at 17:25
  • Yes thank you, this is the first time that i have to load first a data and use them in the future, i was a little bit confused why did this happened Commented Dec 23, 2017 at 17:38

2 Answers 2

5

The result of getData is always a Promise that resolves to your data. To access the values, you can use async/await:

(async () => {

    let notes = await getData("notes");
    let pentagrama = await getData("pentagrama");

    // use them here

})();

Alternatively, you can use Promise.all to wait for both promises to resolve, and then access the received data:

let notesP = getData("notes");
let pentagramaP = getData("pentagrama");

Promise.all([noteP, pentagramaP]).then(res => {

    let notes = res[0];
    let pentagrama = res[1];

    // use them here

});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, both worked for me, i was expecting that when i use the .then method with the return that would be the actual value of the variable.
1

ASYNC

AWAIT

This will work for you if you just want to check the response in your Google Chrome console because in the console you can use await without an async function which probably could be because everything executed in the console is wrapped in an async function by default(just a speculation).

ONLY WORKS IN CONSOLE:

const getData = (file) => (
  fetch(`./assets/resources/${file}.json`).then(data => data.json());
)

let notes = await getData("notes")
let pentagrama = await getData("pentagrama")

But if you want to get this working in an application, remember that you ALWAYS need to wrap an await inside async

TO GET IT WORKING IN AN APPLICATION:

const getData = async (file) => (
  await fetch(`./assets/resources/${file}.json`).then(data => data.json());
)

const wrapperFunc = async () => {  
  let notes = await getData("notes")
  let pentagrama = await getData("pentagrama")
}

1 Comment

Oh thank you so much, didn't know this information, good to know for the future

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.