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?

Phil
  • 157,677
  • 23
  • 242
  • 245
  • Have you tried using axios? https://github.com/axios/axios IMO, is way more robust than fetch. – Dave Pastor May 01 '20 at 02:57
  • 2
    @DavePastor ...doesn't including an additional library for such a simple solution seem like overkill to you? – esqew May 01 '20 at 03:02
  • @esqew not at all, in real life project you'd use a library like that one. But you can try promise chains – Dave Pastor May 01 '20 at 03: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. – esqew May 01 '20 at 03:17
  • Fair point, so a basic point you can make while defending your thoughts and validating them is the following: "One of the main selling points of Axios is its wide browser support. Even old browsers like IE11 can run Axios without any issue. Fetch(), on the other hand, only supports Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+". One more: "Axios automatically stringifies the data when sending requests (though you can override the default behavior and define a different transformation mechanism). When using fetch(), however, you’d have to do it manually." And it is battle tested library. – Dave Pastor May 01 '20 at 03:22
  • I'd have preferred not to use any libraries as I'm just learning JS as well. I think I will check out axios. – danieldcaesar May 01 '20 at 03:31
  • 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. – LearningEveryday May 01 '20 at 03:44
  • @LearningEveryday I did that but I'm still getting the promise. I'll try axios and update later – danieldcaesar May 01 '20 at 03:57
  • @danieldcaesar you'll still end up with a promise with Axios. That's the idea behind asynchronous functions (and any async operation in JavaScript). You have to deal with the result as a promise – Phil May 01 '20 at 03:58
  • To be fair, I've only been using javascript for about 2 weeks so most of these concepts are very new to me. I will do more reading though. – danieldcaesar May 01 '20 at 04:12

1 Answers1

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>
Phil
  • 157,677
  • 23
  • 242
  • 245
esqew
  • 42,425
  • 27
  • 92
  • 132
  • 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. – danieldcaesar May 01 '20 at 03:33
  • 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. – esqew May 01 '20 at 03:47
  • 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 `
    `, the Snippets console didn't seem to be working as expected.)
    – esqew May 01 '20 at 03:49
  • @Phil - thanks for the edit, much appreciated. – esqew May 01 '20 at 03:55
  • 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 – Phil May 01 '20 at 03:57