Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the result from a fetch function in javascript

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)

like image 580
Benjamin Kantor Avatar asked Sep 11 '25 07:09

Benjamin Kantor


1 Answers

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
  });
like image 114
Maurici Abad Avatar answered Sep 13 '25 21:09

Maurici Abad