BCA Student Stories & UpdatesLive
Async/Await Syntax & Browser fetch() API Fundamentals
The async/await syntax introduced in ES2017 is syntactic sugar built on top of Promises. Combined with the native fetch() API, it provides a readable way to communicate with remote REST APIs and cloud servers.
Day 38 Step-by-Step Practical Flow
🎯1. What You Will Learn Today
Async/Await Syntax & Browser fetch() API Fundamentals — Comprehensive Practical Guide
Har concept ko visual mental models, code anatomy aur practical industry tips ke sath samjhein.
The async/await syntax introduced in ES2017 is syntactic sugar built on top of Promises. Combined with the native fetch() API, it provides a readable way to communicate with remote REST APIs and cloud servers.
"Think of async/await like waiting for a message reply on your phone: instead of writing a complex contract with multiple handlers, you simply wait (await) for the message to arrive, and if there is no signal, your try...catch handles the error."
👨🏫3. Teacher Demonstration Code
See how remote quotes are fetched, parsed, and rendered with loading and error handling.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: 'Segoe UI', sans-serif; background: #060c18; color: #fff; padding: 24px; text-align: center; }
.card { max-width: 480px; margin: auto; background: #0c1328; border: 1px solid #1e293b; padding: 24px; border-radius: 12px; }
button { padding: 10px 18px; background: #2563eb; color: #fff; border: none; border-radius: 6px; font-weight: bold; cursor: pointer; }
.quote { font-style: italic; font-size: 16px; color: #38bdf8; margin: 18px 0; }
.author { font-size: 13px; color: #94a3b8; font-weight: bold; }
.error { color: #ef4444; margin-top: 10px; }
</style>
</head>
<body>
<div class="card">
<h3>💡 Developer Quote of the Day</h3>
<button id="fetchBtn">Fetch New Quote</button>
<div id="contentBox">
<p class="quote" id="quoteText">Click button to fetch from API...</p>
<p class="author" id="authorText"></p>
</div>
<div class="error" id="errorBox"></div>
</div>
<script>
const btn = document.getElementById("fetchBtn");
const quoteText = document.getElementById("quoteText");
const authorText = document.getElementById("authorText");
const errorBox = document.getElementById("errorBox");
async function loadQuote() {
btn.disabled = true;
btn.textContent = "Loading...";
errorBox.textContent = "";
try {
// Fetch from public dummy REST API
const response = await fetch("https://dummyjson.com/quotes/random");
// Guard against HTTP 404 / 500
if (!response.ok) {
throw new Error("HTTP Error " + response.status + ": Failed to retrieve quote");
}
const data = await response.json();
quoteText.textContent = '"' + data.quote + '"';
authorText.textContent = "— " + data.author;
} catch (err) {
errorBox.textContent = "Failed to load quote. Check internet connection. (" + err.message + ")";
} finally {
btn.disabled = false;
btn.textContent = "Fetch New Quote";
}
}
btn.addEventListener("click", loadQuote);
</script>
</body>
</html>2. Hands-On Practical Lab: Follow Instructions in VS Code
Code like a professional software engineer! Follow the step-by-step instructions below in Visual Studio Code (VS Code) on your PC, test your output locally, and push to GitHub.
Day 38 Practical Task Test Studio
Declare an async function and use await fetch("https://jsonplaceholder.typicode.com/users").
Verify if (!response.ok) throw new Error() and extract data with await response.json().
The "fetch does not reject on 404" Trap
Tap or click on the exact line below that contains the error:
Click any code lineasync function getUser(id) { try { // ❌ Bug: If endpoint returns 404 Not Found, fetch DOES NOT jump to catch! const res = await fetch("https://api.example.com/users/99999"); const data = await res.json(); displayUser(data); // 💥 Displays broken empty card or crashes on data properties! } catch (err) { console.error("Network error:", err); }}Senior Developer Forensic Analysis:
Unlike libraries like Axios, window.fetch() only rejects when a network error occurs (like no internet connection). If the server responds with 404 Not Found or 500 Internal Server Error, fetch() still successfully resolves! You must manually check if (!res.ok).
📝Independent Practice: Assignment
📄 index.htmlUniversity News Feed & Technical Blog Reader SPA
- •Fetch blog posts or articles from a public REST API (e.g. JSONPlaceholder /posts).
- •Display a Skeleton Loader animation while the API request is in-flight.
- •Render posts as responsive cards with Title, Excerpt, and Read More buttons.
- •Handle network disconnects gracefully by showing a "Retry Connection" button.
Open Visual Studio Code on your PC (code .), create index.html, paste this complete step-by-step verified code, test in your browser, and push to your GitHub repo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BCA Day 38 - REST API Feed</title>
<style>
body { font-family: 'Segoe UI', sans-serif; background: #060c18; color: #fff; padding: 24px; }
.container { max-width: 680px; margin: auto; }
.header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
button { padding: 10px 16px; background: #2563eb; color: #fff; border: none; border-radius: 6px; font-weight: bold; cursor: pointer; }
.post { background: #0c1328; border: 1px solid #1e293b; padding: 18px; border-radius: 10px; margin-bottom: 12px; }
.post h3 { margin-top: 0; color: #38bdf8; text-transform: capitalize; }
.post p { color: #94a3b8; font-size: 14px; line-height: 1.5; }
.loader { text-align: center; padding: 24px; color: #38bdf8; font-weight: bold; display: none; }
.error-card { background: #450a0a; border: 1px solid #dc2626; padding: 16px; border-radius: 8px; color: #fca5a5; display: none; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h2>📰 Tech News Feed (REST API)</h2>
<button id="refreshBtn">↻ Refresh</button>
</div>
<div class="loader" id="loader">Fetching articles from server... ⏳</div>
<div class="error-card" id="errCard"></div>
<div id="postsList"></div>
</div>
<script>
const loader = document.getElementById("loader");
const errCard = document.getElementById("errCard");
const postsList = document.getElementById("postsList");
const refreshBtn = document.getElementById("refreshBtn");
async function fetchPosts() {
loader.style.display = "block";
errCard.style.display = "none";
postsList.innerHTML = "";
refreshBtn.disabled = true;
try {
const res = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=4");
if (!res.ok) throw new Error("HTTP error " + res.status);
const posts = await res.json();
posts.forEach(p => {
const div = document.createElement("div");
div.className = "post";
div.innerHTML = '<h3>' + p.title + '</h3><p>' + p.body + '</p>';
postsList.appendChild(div);
});
} catch (err) {
errCard.style.display = "block";
errCard.textContent = "Failed to fetch articles: " + err.message + ". Please try again.";
} finally {
loader.style.display = "none";
refreshBtn.disabled = false;
}
}
refreshBtn.addEventListener("click", fetchPosts);
fetchPosts();
</script>
</body>
</html>🎓4. Viva Check: Mandatory Conceptual Test
Why does window.fetch() NOT reject its Promise when the server responds with a 404 Not Found error?
5. Mandatory Step: Push to GitHub to Unlock Next Lesson
Target Repo: html-css-projects
Exact GitHub Setup Guide & Expected Structure
Day 38 RequirementsFollow these exact folder and file names to prevent verification errors.
index.html: Avoid spaces or custom names like Alan Turing..html or Index.HTML. Linux/GitHub servers are strictly case-sensitive.day-38/ for today so you don't overwrite previous days.main.You are welcome to read all notes, inspect code snippets, and practice all exercises of Day 38 freely! To officially submit your GitHub repository and unlock subsequent days in your portfolio, please complete Day 37: Asynchronous JavaScript: Callbacks, Promises & Promise Chaining first.
Complete Day 37 First