6

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.

Ced
  • 15,847
  • 14
  • 87
  • 146
  • 1
    basically, it's so that one can process responses larger than the available RAM. as an aside, you don't need anon wrappers for each promise. write a re-usable helper or two to cut down cruft – dandavis Aug 14 '16 at 21:59

1 Answers1

10

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.

Karin
  • 8,404
  • 25
  • 34