Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  99] [ 4]  / answers: 1 / hits: 52560  / 8 Years ago, sun, september 11, 2016, 12:00:00

I've just started to learn the Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch



Here's a code snippet which I wrote to tinker around with it:



fetch('http://swapi.co/api/people/1')
.then(function(response) {
var json = response.json();

console.log(json);
// Expected : { name: Luke Skywalker,height: 1.72 m, ... }
// Get : Promise {[[PromiseStatus]]: pending, [[PromiseValue]]: undefined}
});


I would have expected to get an JSON object out of response.json().



Similar to what you get when using JSON.parse().



Instead I get a promise object.



If I enlarge the promise chain like shown here ...



return response.json().then(function(json) {
// process your JSON further
});


... then it works: Within the then method of the following promise it appears as json.



Why can't I retrieve the JSON data within the then() of the first promise?



Can anyone please explain what is going on here?



I would really much appreciate it.


More From » json

 Answers
4

because response.json() returns another promise (which is within your function body)



https://developer.mozilla.org/en-US/docs/Web/API/Body/json


[#60750] Thursday, September 8, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tina

Total Points: 91
Total Questions: 106
Total Answers: 104

Location: Vanuatu
Member since Fri, May 13, 2022
2 Years ago
;