≡ Menu

💻 Async/Await with the Fetch API: A Quick Tutorial

The Fetch API is the modern standard for making network requests in the browser, and pairing it with async and await provides the cleanest, most readable way to handle asynchronous operations.

Understanding async and await

 

  • async: This keyword is placed before a function declaration (async function getData() { ... }) to indicate that the function will always return a Promise.

  • await: This keyword can only be used inside an async function. It pauses the execution of the async function until the Promise it precedes is resolved (or rejected), effectively making asynchronous code look and behave like synchronous code.

Step-by-Step GET Request Example

 

Here is a template for fetching JSON data using async/await and the fetch API.

1. Define the async Function

Start by defining your function with the async keyword. It’s best practice to wrap your asynchronous code in a try...catch block to handle potential errors.

async function fetchData(url) {
  try {
    // ... code to fetch and process data
  } catch (error) {
    // ... code to handle errors
  }
}

2. Fetch the Resource

 

Use await before the fetch() call. The fetch() function returns a Promise that resolves to a Response object.

const response = await fetch(url);

3. Check for HTTP Errors

The fetch API’s promise only rejects on network errors (like a dropped connection). It does not reject on HTTP error status codes like 404 or 500.

You must manually check the response’s ok property, which is true for a 200-299 status range

if (!response.ok) {
  throw new Error(`HTTP error! Status: ${response.status}`);
}

4. Extract the JSON Data

 

The Response object has a .json() method which returns a Promise that resolves to the parsed JSON data. Use await again to pause execution until the data is fully parsed.

const data = await response.json();
return data;

Complete GET Example

 

async function fetchPost(id) {
  const url = `https://jsonplaceholder.typicode.com/posts/${id}`; // Example API URL
  try {
    let response = await fetch(url);

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    let data = await response.json();
    console.log("Fetched Data:", data);
    return data;
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

fetchPost(1);

🛠️ Handling Other Request Methods (POST/PUT/DELETE)

 

To use other HTTP methods like POST, you need to pass a second argument to fetch()—an options object. This object specifies the method, headers, and a body for the request.

POST Example

To send data (e.g., a new post), you must include:

  • method: 'POST'

  • headers: Crucially, Content-Type: 'application/json' tells the server to expect JSON data.

  • body: The data you are sending, converted to a JSON string using JSON.stringify().

async function createPost(postData) {
  const url = 'https://jsonplaceholder.typicode.com/posts';
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(postData),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const newPost = await response.json();
    console.log("New Post Created:", newPost);
    return newPost;
  } catch (error) {
    console.error("Error creating post:", error);
  }
}

createPost({ title: 'My New Post', body: 'This is the content.', userId: 1 });

Useful links below:

Let me & my team build you a money making website/blog for your business https://bit.ly/tnrwebsite_service

Get Bluehost hosting for as little as $1.99/month (save 75%)…https://bit.ly/3C1fZd2

Best email marketing automation solution on the market! http://www.aweber.com/?373860

Build high converting sales funnels with a few simple clicks of your mouse! https://bit.ly/484YV29

Join my Patreon for one-on-one coaching and help with your coding…https://www.patreon.com/c/TyronneRatcliff

Buy me a coffee ☕️https://buymeacoffee.com/tyronneratcliff

{ 0 comments… add one }

Leave a Comment