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 Merge Objects in JavaScript
How to Merge Objects in JavaScript

How to change opacity on hover in CSS
How to change opacity on hover in CSS

What is JavaScript Array.pop() Method?
What is JavaScript Array.pop() Method?

How to loop through a 2D array in JavaScript
How to loop through a 2D array in JavaScript

Answers by CoreUI Core Team