Retrieiving JSON data

I’ve just started with JS with a clear end goal in mind. It’s a bit of a means to an end. I have a JSON file that I need to get data from for use in a formula. It has variables for each year and that part works fine. The JS code (or rather the html) file reads as follows:

<!DOCTYPE html>

<html>

<body>

<h2>ARRAYS</h2>

<p id="demo">

</p>

<script>

   var year = 2020;

var want = "y" + year;

console.log(want);


   async function myFetch() {

 let  myrates = await fetch('./convertcsv.json')

  .then(function(resp) {

      return resp.json();

  })

  .then(function(data) {

      console.log(data);

      document.getElementById("demo").innerHTML = data[want].BRB;
        

  })

  const BRB=data[want].BRB;

  console.log(BRB);

}
</script>
</html>

Everything works fine right up until the const BRB line where the console shows "Uncaught (in promise) data is not defined at myFetch. I’ve a feeling its a scope issue but don’t know nearly enough to fix it. Can anyone help out? Thanks in advance.

this code:

  const BRB=data[want].BRB;

  console.log(BRB);

is not in the then callback function. So code moved to the then callback function.

now this code runs before the promise is resolved

ANd that worked a treat. Thanks very much.

As a follow up, if I put the const in the then callback but move the console.log statement outside of it it fails again. Other than taking the consoloe.log statement inside the then is there any way to make it work?

Why would you want this?

Not entirely sure as yet, was just looking for options if possible.

Actually, lost sight of what I was trying to do. The idea of the fetch is to get the external data to feed into constants. Those will then be needed in a lot of different places on the ensuing HTML page (and the JS formula as well). My (very old school) programming brain says pick up all the constants I need at the start and then keep them in memory to be used until the page has finished. That make sense?

PS the idea was to hive off the script to get the constants to a different file as I’ll need to use the formulas in the file across a lot of pages. Calling the function to get the constants to pass to the calculation formula was what I had in my head.

you can make functions:

const functionOne = (data) => {
   // 
}

const functionTwo = (data) => {
   // 
}

which you can call from your callback:

 .then(function(data) {
    functionOne(data);
    functionTwo(data);
 })

or you could even make an object with methods.

1 Like

Looks like I’ve got some reading to do then! Thanks for the help.

if you want more reading, I like async and await keywords a lot more. Which is some syntactical sugar to work with promises:

https://www.loginradius.com/blog/async/callback-vs-promises-vs-async-await/

Thanks. I’ll take a look at that too and see what works best for what I need to happen.

1 Like