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"
}
]
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));
In this code:
- The
fetch()
method retrieves the data from provided location, in our case, it isdata.json
file. - The first
.then()
method converts the response back to JSON format withres.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();
In this version:
- We define an
async
function calledfetchData()
. - 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.
The reason is that they don’t have access to reading your internal files. To fix this, you can either:
- 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)
The result:
- 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.
- Push your project to GitHub.
- In your repository, go to
Settings
>Pages
. - 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.