Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch api, why do I have to use then on the response json(), trying to make sens of promises [duplicate]

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.

like image 643
Ced Avatar asked Aug 14 '16 21:08

Ced


1 Answers

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.

like image 109
Karin Avatar answered Sep 18 '22 02:09

Karin