0

So I was trying to bring out a variable named data that's storing the value 42 from a .then() method from the following code which console logs 42:

fetch("http://localhost:8088/get/value")
.then(response => response.json())
.then(data => console.log(data));

I was told I wouldn't be able to do that and that I should try await/async so I readjusted my code to:

asyncCall();

async function asyncCall()
{
    var a = await fetch("http://localhost:8088/get/value");
    console.log(a);
}

and it ends up console logging the whole response but weirdly it registers false for whether the body is used or not when I thought that the value 42 was sent through the body. Why did the value 42 seemingly disappear when before I was logging it fine? -And what can I do so that it console logs the original value 42 with async/await? Thanks for the future help.

CrimsonTide0
  • 37
  • 1
  • 6

1 Answers1

0

You're missing the call to response.json() that you had in the first version. This tells the fetch module to interpret the response body as json, otherwise, it may be a buffer or something else.

asyncCall();

async function asyncCall()
{
    let data = await fetch("http://localhost:8088/get/value").then(res => res.json());
    console.log(data);
}
Klaycon
  • 10,599
  • 18
  • 35
  • @CrimsonTide0 Why would you have to do this little async song and dance if you could simply end up with a variable that was obtained synchronously? Then there would be no point. In order to use the result of your `fetch`, you simply don't have a choice but to use `await` or `.then()` to resolve the promise and *use it in that resolved context* instead of trying to yank the value out of the future. See https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call for more – Klaycon Jul 29 '20 at 21:02