Async/Await and Fetch API
Async/Await and Fetch API
Write Async Code That Reads Like Sync
By AI Learning Assistant · JavaScript · Async/Await · Fetch API
🤖 AI-POWERED LESSON
This article is paired with a live AI session. As you read, you will see real questions asked to an AI assistant and the answers that came back, showing you exactly how to use AI to master Async/Await and the Fetch API.
Promises were a huge improvement over callbacks, but they still had a bit of a learning curve. Then Async/Await arrived. It lets you write asynchronous code that looks and feels like synchronous code. No more chaining .then() and .catch() just regular variables, regular try/catch, and regular looking code that happens to wait for things.
Think of Async/Await as putting a bookmark in your code. The await keyword says "pause right here until this Promise resolves, then assign the result to this variable." Meanwhile, JavaScript isn't actually frozen it can still handle other tasks. The syntax just makes it look like you're waiting.
We will cover async functions, the await keyword, try/catch error handling, the Fetch API for making real HTTP requests, parsing JSON responses, and the difference between Fetch and Axios. By the end, you will be fetching data from real APIs like a professional.
What is Async/Await?
SYNCHRONOUS LOOKING · ASYNCHRONOUS BEHAVIOR
The async keyword turns a regular function into a function that always returns a Promise. Inside an async function, you can use the await keyword. Await pauses the execution of that function until the Promise you're awaiting resolves, then returns the resolved value. If the Promise rejects, await throws the error, which you can catch with try/catch.
This is revolutionary because it eliminates the need for .then() chains. Your code becomes linear and readable. You can use regular loops, conditionals, and try/catch blocks exactly as you would in synchronous code.
⚠️ AWAIT ONLY WORKS INSIDE ASYNC
You can only use the await keyword inside a function marked with async. If you try to use it at the top level (outside any function), you'll get a syntax error. Modern browsers now support top-level await in modules, but the safest approach is always inside an async function.
The Fetch API
MAKE REAL HTTP REQUESTS · GET · JSON
The Fetch API is modern JavaScript's built-in way to make HTTP requests. It returns a Promise that resolves to a Response object. That Response object has methods like .json(), .text(), and .blob() to parse the response body. The key thing to remember: the first await gives you the response headers, the second await gives you the actual data.
📡 FETCH REAL DATA FROM PUBLIC API (JSONPlaceholder)
// Async function to fetch user data from a public API async function getPublicCourses() { try { // Step 1: Make the HTTP request and wait for the response const response = await fetch("https://jsonplaceholder.typicode.com/users"); // Step 2: Check if the request was successful (status code 200-299) if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } // Step 3: Parse the JSON body from the response (this also returns a Promise) const data = await response.json(); // Step 4: Work with the data (take first 5 users and log them) data.slice(0, 5).forEach(user => { console.log(`Student: ${user.name} | Email: ${user.email}`); }); } catch (error) { // Handle any error that occurred during fetch or parsing console.log("Something went wrong:", error); } } // Call the async function getPublicCourses();
🌐 Live Demo: Fetch Real Users from JSONPlaceholder
Click the button to fetch real user data from a public API. The console will also show the results.
✅ WHY THIS PATTERN WORKS
The try/catch block wraps all asynchronous operations. If fetch fails (network error, wrong URL), or if response.json() fails (invalid JSON), or if the response.ok is false (404, 500), the error is caught and handled gracefully. This is much cleaner than .catch() chaining.
Error Handling with Try/Catch
GRACEFUL FAILURE · USER FRIENDLY MESSAGES
In synchronous code, errors bubble up and crash your program unless you catch them. With async/await, errors work the same way — but they come from rejected Promises. The try/catch block catches both synchronous errors and rejected Promises. This makes error handling unified and predictable.
A common mistake is forgetting to check response.ok. Fetch only rejects the Promise on network failures, not on HTTP error statuses like 404 or 500. That's why we manually check if (!response.ok) and throw our own error.
Multiple Requests with Promise.all()
PARALLEL FETCHING · FASTER APPS
Sometimes you need to fetch data from multiple endpoints. You can await them sequentially, but that's slow. Instead, use Promise.all() to run them in parallel. With async/await, it's just as clean.
Quick Comparison
| FEATURE | Fetch | Axios |
|---|---|---|
| Installation | Built in (0 KB) | npm install axios (~13 KB) |
| JSON parsing | Manual (await res.json()) | Automatic (response.data) |
| HTTP error handling | Must check response.ok | Rejects Promise automatically |
| Request/Response interceptors | Manual implementation | Built in |
| Node.js support | Requires node-fetch | Native |
| Best for | Simple requests, lightweight apps | Complex apps, interceptors, retries |
🤖 HOW AI ACCELERATES THIS TOPIC
Ask AI: "Convert this Promise .then() chain to async/await syntax." Get instant refactoring with proper error handling.
Ask: "My fetch request is failing with a CORS error. What does this mean and how do I fix it?" The AI explains Cross-Origin Resource Sharing and solutions.
Ask: "Write an async function that fetches user data, handles loading states, and shows errors in the UI." Get production-ready code with loading spinners and error messages.
AI-Assisted JavaScript Learning · Async/Await & Fetch API · Real World Data Fetching
Complete this lesson
Mark as complete to track your progress