I'm trying to understand promises so I tried a simple get request on twitch. What I don't understand is why does json()
returns a promise. Why ? The response already has the data in it so why the hell is it a promise ?
fetch('https://api.twitch.tv/kraken/games/top?limit=10&offset=0')
.then( resp => {
resp.json()
.then(function(data) {
console.log(data);
});
});
In other words : The first then
, I understand, it waits for the response. However when entering the then function it means that the response has been received thus the data should be immediately accessible without the need of yet another promise. It just confuses me.
From the docs:
The response of a fetch() request is a Stream object, which means that when we call the json() method, a Promise is returned since the reading of the stream will happen asynchronously.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With