0

I'm trying to figure out how to save the output of a fetch to a variable. My aim is to use it as an object.

Here is my code:

async function getWeather() {
    let response = await fetch('url');
    let result = await response.json();
    return console.log(result);
}
getWeather();

That code gives me the expected response

the expected response

I tried to return the result instead of a console log and store it in a variable (let weather=getWeather();) which gave me the promise object

the promise object

when I console logged weather.

I also tried another solution for this question that was answered here, but when I tried to console log the object outside of the fetch, I would get undefined.

Is there any other solution?

10
  • Have you tried using axios? github.com/axios/axios IMO, is way more robust than fetch. Commented May 1, 2020 at 2:57
  • 2
    @DavePastor ...doesn't including an additional library for such a simple solution seem like overkill to you? Commented May 1, 2020 at 3:02
  • @esqew not at all, in real life project you'd use a library like that one. But you can try promise chains Commented May 1, 2020 at 3:07
  • 3
    @DavePastor I'm not sure what "real life" projects you've worked on in the past, but I'd find it extremely difficult to sit in a code review & defend the addition of any libraries to a project when the language's built-in features could provide the same exact functionality in the same amount of lines of code. If the library has already been included in the project to enable more advanced functionality, that'd be a different story, but in this case I would hesitate to recommend the inclusion of the addition of any libraries. I'd be curious to hear if you believe something to the contrary. Commented May 1, 2020 at 3:17
  • 2
    axios is what I use in most of the cases, but in your case it may not help. You will just use axios instead of fetch. You may run into the same issue. Remove the second await and instead of returning console.log, return the result. Let us know how it goes. Commented May 1, 2020 at 3:44

1 Answer 1

1

You've defined it as an async function, it will always return a Promise first.

Use the await keyword in your console.log() call to await for the returned value.

async function getWeather() {
    let response = await fetch('https://api.weather.gov/alerts');
    let result = await response.json();
    return result;
}

(async () => {
    document.querySelector("#output").innerText = JSON.stringify(await getWeather(), null, 2);
})();
<pre id="output"></pre>

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

5 Comments

Wouldn't await only work in an async function? And I'm getting Uncaught SyntaxError: missing ) after argument list when I try that. I'm getting that error in the code snippet you sent as well.
You're right - thanks for pointing that out. I've updated my snippet to illustrate how you can use await in this kind of context. As far as the syntax error, I saw this too; I believe the JSON I've set up to retrieve from for this small snippet/demo is malformed, but let me take another look to ensure this is the case.
I've updated my snippet - I believe the "syntax error" that was being thrown was a (weird) side effect of await not being leveraged within an async function - my apologies again. (Also - I've re-factored to output the object as text to a <div>, the Snippets console didn't seem to be working as expected.)
@Phil - thanks for the edit, much appreciated.
You could shorten this somewhat by just having return response.json(). There's no need to await the .json() promise if you immediately return the result

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.