01 / 21

Async Fetch &
UI Updates

Learn how to request data from APIs using fetch, handle responses with async/await, and dynamically update the DOM with the results.

JavaScript

What Is Asynchronous Code?

JavaScript is single-threaded: it runs one instruction at a time. When you need to do something slow, like fetching data from a server, you don't want the entire page to freeze while waiting.

Asynchronous code lets JavaScript start a task and move on to other work. When the slow task finishes, a callback fires and your code picks up where it left off.

The fetch() API

fetch() is a built-in browser function that sends an HTTP request and returns a Promise. A Promise is an object that represents a value that may not exist yet but will resolve in the future.

fetch(url)
Sends a GET request to the given URL and returns a Promise that resolves to a Response object.
response.json()
Parses the Response body as JSON and returns another Promise that resolves to real JavaScript data.

A Promise Has Three States

Pending Waiting... Fulfilled Has a value ✓ Rejected Has an error ✕ .then() .catch() new Promise() A Promise settles exactly once: either fulfilled or rejected

The async/await Pattern

async/await is syntactic sugar over Promises. It lets you write asynchronous code that reads like synchronous code: top to bottom, no nested callbacks.

async function getData() { const response = await fetch('https://api.example.com/data'); const data = await response.json(); return data; }
async
Marks a function as asynchronous. It always returns a Promise, even if you return a plain value.
await
Pauses execution inside an async function until the Promise settles, then unwraps the resolved value.

.then() Chains vs async/await

.then() Chains async/await
Readability Nested callbacks, harder to follow Linear, top-to-bottom
Error handling .catch() at end of chain try/catch block
Debugging Stack traces can be confusing Stack traces are clearer
Under the hood Promises Also Promises!

Error Handling with try/catch

Network requests can fail: the server might be down, the URL might be wrong, or the user might be offline. Always wrap your fetch calls in a try/catch block.

async function loadUser() { try { const res = await fetch('/api/user'); if (!res.ok) throw new Error(`HTTP ${res.status}`); const user = await res.json(); console.log(user); } catch (err) { console.error('Fetch failed:', err); } }

The Fetch-Parse-Render Flow

1. fetch(url) Send HTTP request 2. await response Get Response object 3. await .json() Parse JSON body 4. JS Object/Array Real data to work with 5. Update DOM Show to user catch (error) Show error message The complete async fetch pipeline

How to Apply the Pattern

1
Write an async function. Put the async keyword before the function declaration.
2
Wrap logic in try/catch. This ensures network errors and bad responses are handled gracefully.
3
Await fetch(url). Store the Response object in a variable.
4
Check response.ok. If false, throw an error to trigger the catch block.
5
Await response.json(). Parse the body into a usable JavaScript object or array.
6
Update the DOM. Use createElement, textContent, or innerHTML to display the data on the page.

Example 1: Fetch a Single User

// HTML: <div id="user-card"></div> async function showUser() { try { const res = await fetch('https://jsonplaceholder.typicode.com/users/1'); if (!res.ok) throw new Error('Network error'); const user = await res.json(); const card = document.getElementById('user-card'); card.textContent = user.name; } catch (err) { document.getElementById('user-card') .textContent = 'Failed to load user.'; } } showUser();

Example 2: Render a List of Posts

async function showPosts() { try { const res = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=5'); if (!res.ok) throw new Error('Failed'); const posts = await res.json(); const list = document.getElementById('post-list'); posts.forEach(post => { const li = document.createElement('li'); li.textContent = post.title; list.appendChild(li); }); } catch (err) { console.error(err); } }

Example 3: Loading & Error States

async function loadData() { const container = document.getElementById('output'); container.textContent = 'Loading...'; // Show loading try { const res = await fetch('/api/items'); if (!res.ok) throw new Error(`Status: ${res.status}`); const items = await res.json(); container.textContent = ''; // Clear loading // ... render items } catch (err) { container.textContent = 'Something went wrong.'; } }

DOM Update Techniques

textContent
Sets plain text inside an element. Safe: won't execute scripts. Use for single values like names or numbers.
innerHTML
Sets HTML markup inside an element. Powerful but dangerous if you insert user-supplied data (XSS risk).
createElement
Creates new DOM nodes programmatically. The safest and most flexible approach for building dynamic lists or cards.

Why This Matters

Almost every modern web application fetches data from an API: social media feeds, weather widgets, search results, user profiles. Understanding async/await with fetch is the foundation for:

SPAs
Single Page Applications (React, Vue, Angular) all rely on fetch for dynamic content loading.
APIs
Communicating with backends, third-party services, databases: it all goes through HTTP fetch calls.
UX
Users expect instant, responsive interfaces. Async patterns prevent page freezes and enable smooth interactions.

Common Mistakes

✕ Forgetting await
Writing const data = fetch(url) without await gives you a Promise object, not the actual data. You must await both fetch and .json().
✕ No error handling
Skipping try/catch means a network failure crashes your code silently. Always handle errors and show feedback to the user.
✕ Not checking response.ok
A 404 or 500 status code does NOT reject the fetch Promise. You must manually check response.ok and throw if it's false.
✕ await in the wrong context
The await keyword can only be used inside an async function or at the top level of a modern JavaScript module. Using it in a regular function will cause a syntax error.

Summary Cheat Sheet

Concept What It Does Key Detail
fetch(url) Sends an HTTP request Returns a Promise
response.ok Boolean: was it 200-299? Check before parsing
response.json() Parses body as JSON Also returns a Promise
async Marks function as async Always returns a Promise
await Pauses until Promise settles Only inside async functions
try/catch Handles errors Catches network + thrown errors

Question 1 of 5

What does fetch() return?

Question 2 of 5

What happens if you write const data = fetch(url) without the await keyword?

Question 3 of 5

Why should you check response.ok after a fetch call?

Question 4 of 5

Which DOM method is the safest way to display API data that may include user-generated content?

Question 5 of 5

What is missing from this function that could cause problems in production?