JavaScript data fetching

using other people's data sets with this function
// updated 2025-05-11 11:40

Oftentimes, we wish to consume data from other sources (because we are more into displaying data rather than creating it!)

To fetch data in JavaScript, then, we can use at least three different ways:

  • fetch() function with then
  • fetch() function with async and await (after 2017)
  • XMLHttpRequest and JSON.parse (a very old way)

The fetch() function with then

  • request access to an endpoint
  • after the request finalizes, receive
    • a response (or error) from that endpoint
    • log an error message (if a network error occurred)
  • obtain the response data in JSON format
  • display the data on the front-end
// fill in endpoint here
const url = ''; 

// GET or send error
fetch(url)
.then(response => {
  // if GET successful, return JSON response
  if (response.ok) {
    return response.json();
  }
  // otherwise, return Error
  throw new Error('Request failed!');
}, networkError => {
  // or if there is a network error: 
  console.log(networkError.message);
})
.then(jsonResponse => {
  // we can then do more here with the data
  return jsonResponse;
});

Using async and await

The fetch() function with async and await works for JavaScript versions ES8+ (2017 and later):

// fill in endpoint here
const url = '';

// async keyword waits for await to finish
const getData = async () => {
  try {
    // wait for a response from url
    const response = await fetch(url);
    // then, get the json
    if (response.ok) {
     const jsonResponse = await response.json();
    }
    // bad responses get errors
    throw new Error('Request failed!');
  } catch (error) {
    // if the sky falls
    console.log(error);
  }
}

Using XMLHttpRequest and JSON.parse

Just for posterity's sake, we have this "old" way to fetch JSON data:

const request = new XMLHttpRequest()

request.open('GET', 'data.json', true)

request.onload = function() {
  if (this.status >= 200 && this.status < 400) {
    // if all went well, this is the data
    const data = JSON.parse(this.response)          
    console.log(data)
  } else {
    // otherwise, an error message goes here
  }
}

request.onerror = function() {
  // connection error
}

request.send()

The seemingly arbitrary magic numbers of 200 and 400 are due to:

  • 200 being the HTTP status code for a good "OK" request
  • 400 (and any number in the 400s) being the code for an error
⬅️ older (in textbook-javascript)
📒 JavaScript delay handling
newer (in textbook-javascript) ➡️
JavaScript escape sequences 📒
⬅️ older (in code)
📒 JavaScript delay handling
newer (in code) ➡️
JavaScript escape sequences 📒
⬅️ older (posts)
📒 JavaScript delay handling
newer (posts) ➡️
JavaScript escape sequences 📒