JavaScript 3d ago 5 views 6 min read

How to fetch JSON data with async/await in JavaScript

Learn how to use async/await to fetch JSON data from an API in modern JavaScript. This guide covers the fetch API, error handling, and best practices for asynchronous operations.

Riya K.
Updated 10h ago
Sponsored

Cloud VPS — scale in minutes

Instantly deploy SSD cloud VPS with guaranteed resources, snapshots and per-hour billing. Pay only for what you use.

This tutorial explains how to use the fetch API combined with async/await to retrieve JSON data from a server. You will learn to handle network errors gracefully and manage timeouts in your code. These steps work in both modern browsers and Node.js environments with a compatible runtime.

Prerequisites

  • A modern browser with ES2018 support or Node.js version 14.17.0 or later.
  • Basic understanding of JavaScript promises and the fetch API.
  • Access to a public JSON API endpoint (e.g., https://jsonplaceholder.typicode.com/posts/1).
  • A code editor like VS Code or a simple text editor.

Step 1: Create a basic async function

Define a function using the async keyword. This tells JavaScript that the function will contain await expressions and returns a promise. Inside the function, use await before the fetch call to pause execution until the response is ready.

async function getPostData() {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
  const data = await response.json();
  console.log(data);
}

getPostData();

You will see the JSON object printed to the console. The first await waits for the HTTP request to complete. The second await waits for the response body to be parsed as JSON text.

Step 2: Handle network errors

Network failures like a 404 error or a dropped connection will throw an error. Wrap the fetch call in a try/catch block to catch these errors. Log the error message or display a user-friendly message instead of crashing the application.

async function getPostData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/999');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error.message);
  }
}

getPostData();

If you run this code, the console will display Fetch error: HTTP error! status: 404. The !response.ok check ensures you catch non-2xx status codes before trying to parse the JSON body.

Step 3: Parse the response body

The fetch API returns a Response object, not the raw JSON data. You must call response.json() to convert the text into a JavaScript object. Always await this call because parsing is asynchronous. Check if response.ok is true before parsing to avoid errors on invalid responses.

async function getData() {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');

  // Check status before parsing
  if (!response.ok) {
    throw new Error('Failed to fetch data');
  }

  const jsonData = await response.json();
  console.log(jsonData.title);
}

getData();

This code logs the title of the post. The response.ok property returns true for status codes 200-299. If the server returns a 500 error, the code throws an error immediately.

Step 4: Add a timeout mechanism

Long-running requests can hang indefinitely. Implement a timeout to abort the request if it takes too long. Use the AbortController API to create an abort signal. Pass this signal to the fetch options to cancel the request after a set time.

async function getDataWithTimeout(url, timeout = 5000) {
  const controller = new AbortController();
  const { signal } = controller;

  const timeoutId = setTimeout(() => controller.abort(), timeout);

  try {
    const response = await fetch(url, { signal });
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return await response.json();
  } catch (error) {
    if (error.name === 'AbortError') {
      console.error('Request timed out');
    } else {
      console.error('Fetch error:', error.message);
    }
    throw error;
  } finally {
    clearTimeout(timeoutId);
  }
}

getDataWithTimeout('https://jsonplaceholder.typicode.com/posts/1');

This function sets a 5-second limit. If the request does not complete within 5 seconds, the controller aborts the fetch. The finally block ensures the timeout is cleared even if an error occurs.

Step 5: Fetch multiple resources concurrently

Fetching multiple endpoints sequentially is slow. Use Promise.all to fetch several URLs at the same time. Pass an array of fetch calls to Promise.all and await the result. This improves performance significantly compared to sequential fetching.

async function fetchMultiplePosts() {
  const posts = [
    'https://jsonplaceholder.typicode.com/posts/1',
    'https://jsonplaceholder.typicode.com/posts/2',
    'https://jsonplaceholder.typicode.com/posts/3'
  ];

  try {
    const responses = await Promise.all(
      posts.map(url => fetch(url).then(r => r.json()))
    );
    console.log(responses);
  } catch (error) {
    console.error('Error fetching posts:', error);
  }
}

fetchMultiplePosts();

The code creates an array of fetch promises. Promise.all waits for all of them to resolve. If one fails, the whole promise rejects. This pattern is essential for loading lists of data efficiently.

Verify the installation

Modern browsers do not require installation to use fetch and async/await. However, if you are using Node.js, you must verify that your environment supports these features. Open your terminal and run the following command to check the Node version.

node -v

You should see output like v14.17.0 or higher. If the version is lower, update Node.js using your package manager. For example, on Ubuntu, run sudo apt-get update && sudo apt-get install nodejs. Ensure you have a simple HTML file to test the browser version.




  Fetch Test


  
    async function test() {
      try {
        const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
        const data = await res.json();
        console.log('Fetch works:', data.title);
      } catch (e) {
        console.error('Fetch failed:', e);
      }
    }
    test();
  


Open this file in a browser. The console should log Fetch works: Lorem ipsum dolor sit amet. If you see an error, your browser is too old and needs updating.

Troubleshooting

If your fetch request fails, check the browser console or Node terminal for error messages. Common issues include CORS errors when calling APIs from different domains. If you see a CORS policy error, the server must allow requests from your origin. You cannot fix CORS on the client side; you must configure the server headers.

Another common issue is parsing a non-JSON response. If the server returns HTML instead of JSON, response.json() will throw a syntax error. Check the response.headers.get('content-type') before parsing. Ensure the header contains application/json.

Timeout errors often occur on slow networks. Adjust the timeout value in your getDataWithTimeout function. Increase the time limit if the API is known to be slow. Also, verify that your internet connection is stable. If you are running in a sandboxed environment, ensure outbound traffic is not blocked.

If you encounter a TypeError: Failed to fetch, the network request was blocked by the browser or a proxy. Check your firewall settings and browser extensions. Disable ad blockers temporarily to see if they interfere with the request. Ensure you are using a valid URL. A typo in the API endpoint will cause a 404 error, which you must catch in the try/catch block.

Finally, remember that async/await does not magically prevent errors. You must still handle exceptions manually. Always wrap your fetch logic in a try/catch block. This ensures your application remains stable even when the network fails.

Sponsored

Linux Dedicated Server

Rock-solid Linux dedicated servers with root access, KVM-IPMI and fully managed options. CentOS, Ubuntu, Debian, Rocky and AlmaLinux.

Tags: JavaScriptAsyncWeb DevAJAX
0
Was this helpful?

Related tutorials

Comments 0

Login to leave a comment.

No comments yet — be the first to share your thoughts.