DEV Community

Cover image for How to Fetch a JSON File with JavaScript (Promises vs. Async/Await)
Technophile
Technophile

Posted on

How to Fetch a JSON File with JavaScript (Promises vs. Async/Await)

Hey everyone! Welcome back. In today’s post, I’m going to show you how to fetch a JSON file with JavaScript in two ways: using promises and using async/await. We'll compare both methods and discuss which one might be better for your code.

You can also watch the YouTube video I made:

First, let’s look at the JSON file we want to fetch. It contains simple data about users:

[
  {
    "name": "John",
    "age": 24,
    "city": "New York"
  },
  {
    "name": "Dan",
    "age": 26,
    "city": "London"
  },
  {
    "name": "Mark",
    "age": 25,
    "city": "Berlin"
  }
]
Enter fullscreen mode Exit fullscreen mode

Now, let’s see how we can fetch this data and use it in our javascript file using both approaches. Btw, make sure that files are located in the same folder.

Step 1: Fetching JSON with Promises

Ok, let’s start with promises. We can use the built-in JavaScript fetch() method to retrieve our data:

fetch("./data.json")
  .then((res) => res.json())
  .then((data) => console.log(data))
  .catch((error) => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

In this code:

  • The fetch() method retrieves the data from provided location, in our case, it is data.json file.
  • The first .then() method converts the response back to JSON format with res.json() function.
  • In the next .then() method we handle the JSON data and log it to the console.
  • Finally, .catch() method handles any errors that occur with fetching the data, such as wrong file location.

Step 2: Fetching JSON with Async/Await

Now let’s see how to do the same thing using async/await.

async function fetchData() {
  try {
    const res = await fetch("./data.json");
    const data = await res.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchData();
Enter fullscreen mode Exit fullscreen mode

In this version:

  • We define an async function called fetchData().
  • We are using try and catch block to handle any errors, just like catch() method in our previous example.
  • Inside, we use the await keyword to wait for the fetch request to complete and then converts the response to JSON format, and finally, we receive the data.

Step 3: Which One is Better?

Ok, we now know how to fetch the data. So, what’s the difference between these two approaches?

  • Promises offers a simple way to work with callbacks, but the syntax can become messy and harder to follow when dealing with multiple asynchronous operations.
  • While Async/Await reads more like synchronous code, making it easier to debug and maintain, especially in more complex applications.

In general, async/await is the cleaner and more readable approach, and it’s recommended when you’re working with multiple asynchronous actions or want to avoid the callback hell.

Step 4: Solving Cross-Origin Issues

One quick thing to note: If you try to open the HTML file directly into your browser or run nodejs to see the output of your data, you might encounter a Cross-Origin Request Blocked error.

Cross-Origin Request Blocked error

The reason is that they don’t have access to reading your internal files. To fix this, you can either:

  1. Install the Live Server extension in VS Code, so that it runs your project on a local server. (and, it’s much easier when testing locally)

Live Server extension

The result:

Data fetched in local server

  1. Or deploy your project to a platform like GitHub Pages or Netlify, which we’ll quickly cover now.

Step 5: Deploying the Project to GitHub Pages

Once your project is working locally, you can now deploy it using GitHub Pages.

  1. Push your project to GitHub.
  2. In your repository, go to Settings > Pages.
  3. Select the branch and folder to publish your site.

Once your site is live, you should be good to go.

And there you have it! You now know how to fetch JSON using both promises and async/await.

Top comments (4)

Collapse
 
oculus42 profile image
Samuel Rouse

I know my opinion isn't popular, but when I look at the examples for promises and async/await, the promises is easier for me to follow ten out of ten times. It's less code, less indentation, and can actually be simplified even more.

fetch("./data.json")
  .then((res) => res.json())
  .then(console.log)
  .catch((error) => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

It takes getting used to compared to imperative code, but as you start breaking applications into smaller, composable functions, the promise style can read like the description of the work, allowing you to abstract away the details and understand the intent more easily.

Collapse
 
oculus42 profile image
Samuel Rouse

Also, it appears you have mashed two different articles together. Step 4 and later is completely unrelated to the title or previous steps.

Collapse
 
technoph1le profile image
Technophile

Step 4 and 5 explains how to view the output of fetched data. I tried to open the HTML file directly into browser for testing, and it showed "Cross-Origin" error. And, after searching for Google, I found that it has to be run on a local server to read the json file. Same case with nodejs. When you try node inde.js, it shows a bunch of errors and you can't log the data fetched.

I included them in case because I had the same issue.

Thread Thread
 
oculus42 profile image
Samuel Rouse

Thank you for the clarification. Because we were working only with somewhat abstract snippets in the earlier steps I did not follow the transition to loading a local HTML file.

Local file: access scheme is heavily restricted thanks to many security concerns in the early 2000s.