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
1// fill in endpoint here
2const url = ''; 
3
4// GET or send error
5fetch(url)
6.then(response => {
7  // if GET successful, return JSON response
8  if (response.ok) {
9    return response.json();
10  }
11  // otherwise, return Error
12  throw new Error('Request failed!');
13}, networkError => {
14  // or if there is a network error: 
15  console.log(networkError.message);
16})
17.then(jsonResponse => {
18  // we can then do more here with the data
19  return jsonResponse;
20});

Using async and await

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

1// fill in endpoint here
2const url = '';
3
4// async keyword waits for await to finish
5const getData = async () => {
6  try {
7    // wait for a response from url
8    const response = await fetch(url);
9    // then, get the json
10    if (response.ok) {
11     const jsonResponse = await response.json();
12    }
13    // bad responses get errors
14    throw new Error('Request failed!');
15  } catch (error) {
16    // if the sky falls
17    console.log(error);
18  }
19}

Using XMLHttpRequest and JSON.parse

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

1const request = new XMLHttpRequest()
2
3request.open('GET', 'data.json', true)
4
5request.onload = function() {
6  if (this.status >= 200 && this.status < 400) {
7    // if all went well, this is the data
8    const data = JSON.parse(this.response)          
9    console.log(data)
10  } else {
11    // otherwise, an error message goes here
12  }
13}
14
15request.onerror = function() {
16  // connection error
17}
18
19request.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
newer (in textbook-react) ➡️
React — an introduction ⚛️
⬅️ older (in code)
📒 JavaScript delay handling
newer (in code) ➡️
JavaScript escape sequences 📒
⬅️ older (posts)
📒 JavaScript delay handling
newer (posts) ➡️
JavaScript escape sequences 📒