Logo
Published on

Understanding Fetch with async/await

Authors
  • Name
    Twitter

Using fetch with async/await in JavaScript allows you to make asynchronous HTTP requests to external resources, such as APIs, in a clean and readable way. Here's a concise three-line theory, followed by three paragraphs explaining the concept, and three examples demonstrating its usage:

Three-Line Theory:

  1. fetch is a built-in JavaScript function used for making HTTP requests.
  2. When combined with async/await, it allows you to write asynchronous code for handling responses.
  3. When combined with async/await, it allows you to write asynchronous code for handling responses.

Explanation:

When you use fetch with async/await, you can initiate an HTTP request and wait for the response without blocking the main thread. This is particularly useful for fetching data from APIs or performing other network operations. By marking a function as async, you enable the use of the await keyword inside that function, which can be used to pause the execution until the fetch operation is complete.

💡 Learn how to check for an empty object in JavaScript Here are three examples illustrating how to use fetch with async/await:

Example 1: Fetching JSON data

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data.json')
    const data = await response.json()
    console.log(data)
  } catch (error) {
    console.error('Error:', error)
  }
}

fetchData()

In this example, we define an asynchronous function fetchData that fetches JSON data from an API and logs it to the console.

Example 2: Sending POST request with data

async function postData() {
  try {
    const response = await fetch('https://api.example.com/post', {
      method: 'POST',
      body: JSON.stringify({ key: 'value' }),
      headers: {
        'Content-Type': 'application/json',
      },
    })
    const result = await response.json()
    console.log(result)
  } catch (error) {
    console.error('Error:', error)
  }
}

postData()

This example demonstrates how to use fetch with the POST method to send data to an API and receive a response.

Example 3: Handling errors

async function fetchDataWithErrors() {
  try {
    const response = await fetch('https://api.example.com/nonexistent')
    if (!response.ok) {
      throw new Error('Request failed with status ' + response.status)
    }
    const data = await response.json()
    console.log(data)
  } catch (error) {
    console.error('Error:', error.message)
  }
}

fetchDataWithErrors()

In this example, we handle errors by checking the response.ok property and throwing an error if the response status indicates a failure. This illustrates how to handle different scenarios in your fetch requests.

In summary, using fetch with async/await simplifies making asynchronous HTTP requests in JavaScript, making your code more readable and maintainable. It allows you to fetch data from external sources, send data to APIs, and handle errors gracefully.