Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 696
Abhay Jain Avatar asked Aug 18 '16 15:08

Abhay Jain


People also ask

Why is fetch returning promise?

fetch() starts a request and returns a promise. When the request completes, the promise is resolved with the Response object. If the request fails due to some network problems, the promise is rejected. async/await syntax fits great with fetch() because it simplifies the work with promises.

How do you get data out of a fetch promise?

Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

What is the difference between promise and fetch?

The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.

What does the promise returned by fetch () resolve to?

Using Fetch Calling fetch() returns a promise. We can then wait for the promise to resolve by passing a handler with the then() method of the promise. That handler receives the return value of the fetch promise, a Response object.


1 Answers

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

like image 91
SimonR Avatar answered Oct 03 '22 23:10

SimonR