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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With