Fetch returns promise instead of actual data even after using 'then'

Abhay Jain picture Abhay Jain · Aug 18, 2016 · Viewed 20.6k times · Source

I am making a simple fetch call in my component, which looks like this

    var x = fetch(SOME_URL, SOME_POST_DATA)
             .then((response) => response.json())
             .then((responseJSON) => {return responseJSON});

    console.log(x);

The call executes successfully but the console prints a promise instead of data. What am I missing here?

Answer

SimonR picture SimonR · Aug 18, 2016

The way promises works mean you'll need to handle the responseJSON inside the handler for then(). Due to the asynchronous nature of requests the outer code will already have returned by the time the promise resolves.

It can be hard to get your head around at first, but it's much the same as a "traditional" AJAX request - you handle the response in a callback.

To take your example:

var x = fetch(SOME_URL, SOME_POST_DATA)
    .then((response) => response.json())
    .then((responseJSON) => {
       // do stuff with responseJSON here...
       console.log(responseJSON);
    });

More reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise