1

I was looking for this stuff on the internet and I found that: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch. I am relativey new to typescript so there are a few things that confuse me.

First what's the difference between:

fetch('data.json')
.then(function(response) {
    return response.json();
})
.then(function(myJson) {
    console.log(JSON.stringify(myJson));
   //data = myJson;
});

and

fetch('data.json')
.then(function(response) {
    console.log(JSON.stringify(response.json()));
    //data = response.json();
})

The first works well but the second piece of code does't. Why is that? As far as I know fetch retuns the promise of JSON and in .then, response.json() holds the actual JSON object. But the second version doesn't work (I get undefined in console).

My second question is how to get out the value of myJson. I tried doing that with global variable but it didn't work (I get undefined in console):

var data
fetch('data.json')
.then(function(response) {
    return response.json();
})
.then(function(myJson) {
   //console.log(JSON.stringify(myJson));
   data = myJson;
});
console.log(JSON.stringify(data));

1 Answer 1

1

The reason we need to use response.json() is because Fetch returns an HTTP response. To extract the JSON body content from the response, we use json() method.

The reason you are getting undefined is because of async nature of javascript. Try using async and await to solve this issue or print the data inside of the then() not outside of it.

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

2 Comments

But why the first piece of code works and second doesn't. I am using response.json() in both, but the second has an extra .then? And also how can I synchronize this operation? Await needs to be used in async function and I would like for the code below to run synchronously and I couldn't find anything like join() in C++ to do that.
So, In the first one Fetch returns an HTTP response with a lot of overhead like headers and body. Ideally you only need to body section so you use response.json() which resolves a promise and gives you only the needed results. In the second one you are trying to stringify and print a Promise which when being printed may be in pending state. Apparently in JS to make things sync we use Promises or Async Await. Copy all the code below the .then() to inside of .then() and it will act synchronously.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.