this post was submitted on 07 Jul 2023
2 points (100.0% liked)

JavaScript

1988 readers
1 users here now

founded 1 year ago
MODERATORS
 

Absolute JS newbie here. I am able to use fetch() to get JSON from a URL but I can't figure out how to do anything with that JSON outside of the fetch itself.

Here's my code (API key and GPS redacted):

fetch('https://www.airnowapi.org/aq/forecast/latLong/?format=application/json&latitude=X&longitude=X&distance=50&API_KEY=X')
        .then(result => result.json())
        .then((out2) => {     
            console.log('Fetch Output: ', out2);
        }).catch(err => console.error(err)); 

Any code that references out2 other than console.log() call gives an error that out2 is undefined. How do I get access to out2 anywhere else?

you are viewing a single comment's thread
view the rest of the comments
[โ€“] [email protected] 2 points 1 year ago* (last edited 1 year ago)

If you leave out the second 'then()', the return value of the fetch will be your json (wrapped in a Promise). If you're calling fetch in an async function, you can do this:

const out2 = await fetch(url).then(x => x.json()).catch(console.error).

And then out2 will be the exact same as it was in the second 'then', but in the outer scope.

If making your function asyc is not an option, I'm afraid you have to move your logic to the second 'then'.

I recommend looking into javascripts promises. It's the backbone of asynchronous programming, which is very much what you are trying to do.

Good luck, and have fun ๐Ÿ™‚