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

33,643

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

Share:
33,643
Abhay Jain
Author by

Abhay Jain

Github Blog

Updated on August 02, 2022

Comments

  • Abhay Jain
    Abhay Jain almost 2 years

    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?