How to use async/await with fetch in JavaScript

Using async/await with fetch API provides a cleaner, more readable alternative to promise chains for handling HTTP requests in JavaScript. As the creator of CoreUI with over 25 years of JavaScript development experience, I’ve used async/await extensively in production applications for API communication. The most straightforward approach combines async function declarations with await keywords before fetch calls. This pattern eliminates callback hell and makes asynchronous code read like synchronous code while maintaining non-blocking behavior.

Use async/await syntax with fetch to handle HTTP requests in a clean, synchronous-looking manner.

async function fetchUser(id) {
    try {
        const response = await fetch(`/api/users/${id}`)
        const user = await response.json()
        return user
    } catch (error) {
        console.error('Error fetching user:', error)
        throw error
    }
}

// Usage
const user = await fetchUser(123)
console.log(user)

This code declares an async function that uses await to pause execution until the fetch promise resolves. The try/catch block handles both network errors and JSON parsing errors gracefully. The function waits for the response, then waits again for the JSON parsing to complete, making the asynchronous operations appear sequential and easier to understand.

Best Practice Note:

This is the async pattern we use throughout CoreUI backend integrations for reliable data fetching. Always wrap await calls in try/catch blocks to handle errors properly and avoid unhandled promise rejections.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to Detect a Click Outside of a React Component
How to Detect a Click Outside of a React Component

How to Use Bootstrap Dropdown in React the Right Way – with CoreUI
How to Use Bootstrap Dropdown in React the Right Way – with CoreUI

How to get element ID in JavaScript
How to get element ID in JavaScript

How to Center a Button in CSS
How to Center a Button in CSS

Answers by CoreUI Core Team