I'm struggling to get the actual result data from an http fetch in js. I can do it using XMLHttpRequest, but I'd much rather use fetching. I've been trying to get the results from a fetch request like this: fetch('https://api.website.net/?);
I know that you need to assign a then function but nothing I have tried has worked I keep getting more promise objects and no results. I understand vaguely that you need to assign a .then function for once it resolves but I really cannot figure out how to do that.
(This is in browser js not node)
I think that you're getting confused with promises. The fetch function returns a promise and not the data.
I recommend that you read this modern tutorial: https://javascript.info/fetch
This is a very trivial function that gets the url and returns the response data in json:
async function callApi(url) {
const response = await fetch(url);
const data = await response.json();
return data;
}
let data = await callApi('https://api.website.net/?');
// do whatever you want with the data
When dealing with primises there are 2 syntaxes, the old .then()
and the new async
/await
. Using async
/await
is better, in general, so I recommend using the async
/await
syntax. With .then()
it would look like this:
// Not recommended alternative
fetch('https://api.website.net/?')
.then(response => response.json())
.then(data => {
// do whatever you want with the data
});
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