0

I'm doing a little test with json I've turned into a variable using the JS fetch api, I've forgotten about scopes and I can't get the variable with the object outside of the function. I've tried return and other things but nothing has worked.

Code:

fetch(url)
    .then(res => res.json())
    .then((data) => {
        let json = data;
    })
    .catch(err => { throw err });

console.log(json);

Error:

index.js:10 Uncaught ReferenceError: json is not defined

I haven't used JS in a long time, so help would be appreciated. Thanks.

tzcoding
  • 69
  • 6
  • `json` is only defined within the `then` callback, details in [this question's answers](https://stackoverflow.com/questions/500431/). What you need to do is use the data (it's not JSON) at that point, rather than trying to save it for use later. More about doing that in [this question's answers](https://stackoverflow.com/questions/23667086/) and also [this question's answers](https://stackoverflow.com/questions/14220321/). – T.J. Crowder Apr 13 '20 at 13:09
  • Remember that Promises get executed asynchronously, in this case the `console.log` gets executed before any of the `then` code-blocks, so the variable `json` isn't defined. If you want to log the response, you should put `console.log` inside the second `then` block. –  Apr 13 '20 at 13:33

0 Answers0