I'm learning web development so maybe the question is already asked but I haven't found it.
I tried to log response.json() inside the .then method before returning the response.json() promise to the second .then handler function. The problem I'm facing is that although the response.json()'s result is being logged, the code in the next .then method is not being executed.
Here's my code:
const fetchPromise = fetch('https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json');
console.log(fetchPromise)
fetchPromise
.then( response => {
console.log(response.json())
return response.json();
})
.then( json => {
console.log(json[0].name);
});
The code is supposed to log response.json()'s result and then end with logging "baked beans" in the second .then handler, but it just logs the promise object and nothing happens afterwards.
This code, however, seems to work:
const fetchPromise = fetch('https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json');
console.log(fetchPromise)
fetchPromise
.then( response => {
var resp=response.json() // save the value first
console.log(resp)
return resp
})
.then( json => {
console.log(json[0].name);
});
So why does storing the result in a variable work, but directly calling it doesn't?
In the console, you'll see this error:
Uncaught (in promise) TypeError: Failed to execute 'json' on 'Response': body stream already read
That's because you cannot execute response.json() twice.
Simply move the console.log down to the last .then and log json instead of res.json:
fetchPromise
.then( response => {
console.log(response.json()) // remove this line
return response.json()
})
.then( json => {
console.log(json); // add this line
console.log(json[0].name);
});