Guest Mode:

BCA Student Stories & UpdatesLive

You
Your StorySign in & share
Er. Manoj Kumar
D5
Er. ManojActive nowPages
Day 38Advanced JavaScript & Browser APIs2.5 Hours Practical
Push to GitHub to Complete

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.

Interactive Learning Roadmap

Day 38 Step-by-Step Practical Flow

🎯1. What You Will Learn Today

✔Write synchronous-looking asynchronous code using modern async and await keywords.
✔Fetch remote data over HTTP GET using the native window.fetch() API.
✔Check response status using response.ok and response.status before parsing.
✔Extract JSON payloads asynchronously using await response.json().
✔Wrap network calls in robust try...catch blocks to handle connection drops and offline states.
Day 38 MasterclassAdvanced JavaScript & Browser APIs

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.

Real-World Purpose Aur Zaroorat

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.

async Functions: Any function marked async automatically returns a Promise.
await Operator: Pauses function execution until the Promise settles, unpacking the resolved value directly.
Two-Step fetch(): fetch(url) returns a Response object; you must await response.json() to extract parsed data.
The 404/500 Gotcha: fetch() only rejects on network failure (offline/DNS error). HTTP error responses (404, 500) do NOT reject! You must check if (!response.ok).
Error Handling: Use standard try...catch blocks around await statements for clean error management.
Dimaag Mein Bithane Ka Model

"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."

💡 Pro Tip: Code ko ratta mat maaro; imagine karo ki browser har tag ko visually kaise draw karta hai.

👨‍🏫3. Teacher Demonstration Code

See how remote quotes are fetched, parsed, and rendered with loading and error handling.

Consuming Public REST APIs with async/await and response.okhtml
<!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.

2 Coding Tasks
Interactive Coding TestAuto-Evaluates as you type

Day 38 Practical Task Test Studio

Test Score:1 / 2 Passed
1. Practical Task Specifications & Live Test Checklist:Type code below to pass tests
Task 1Implement async/await with fetch

Declare an async function and use await fetch("https://jsonplaceholder.typicode.com/users").

✔ PASSED
Task 2Check response.ok and Extract JSON

Verify if (!response.ok) throw new Error() and extract data with await response.json().

⏳ WAITING
2. Type HTML & CSS Code:index.html
index.html
⚡ Real-Time Testing Active
Tab inserts 2 spaces • Live DOM refresh275 chars
Live Browser Output:
🔒 http://localhost:5500/index.html
Live
Renders live HTML & CSS typed on the left.
Interactive Bug Detective

The "fetch does not reject on 404" Trap

Tap or click on the exact line below that contains the error:

Click any code line
⚠️ Broken Code Inspector
Tap buggy line
1
async function getUser(id) {
2
try {
3
// ❌ Bug: If endpoint returns 404 Not Found, fetch DOES NOT jump to catch!
4
const res = await fetch("https://api.example.com/users/99999");
5
const data = await res.json();
6
displayUser(data); // 💥 Displays broken empty card or crashes on data properties!
7
} catch (err) {
8
console.error("Network error:", err);
9
}
10
}
Stuck? Need a detective clue before checking the solution?

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).

Golden Rule: Always validate code syntax and security attributes before pushing to GitHub!

📝Independent Practice: Assignment

📄 index.html

University 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.
Submission Evaluation Criteria: Push index.html and app.js to your GitHub repository under day-38.
Exact Assignment Solution Code: index.html

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>
Verified Assignment Code Solution (100% Tested & Ready to Run)

🎓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

Windows 11 Terminal / VS Code
1$
mkdir day-38
Create a new project folder (day-38)
2$
cd day-38
Change working directory to day-38
3$
git checkout -b feature/day-38-fetch-api
4$
git add index.html
5$
git commit -m "feat(day-38): implement async await syntax and fetch api rest consumer"
Commit staged changes with a descriptive message
6$
git push origin feature/day-38-fetch-api
Push local commits directly to your remote GitHub repository
⌨️ Paste into terminal:Ctrl + V✨ Word wrap active (no horizontal cutoff)
Completion Prerequisites VerificationIncomplete Steps
Google Login
✔ Required
VS Code Implementation
Step 4 Viva Check
Own GitHub Project
Required

Exact GitHub Setup Guide & Expected Structure

Day 38 Requirements

Follow these exact folder and file names to prevent verification errors.

1. GitHub Repository
html-css-projects
Must be set to Public
2. Exact FolderNEW
day-38/ or bca-day-38/
Create inside repo root
3. Exact File NameREQUIRED
index.html
⚠️ No spaces or custom names
4. What to Submit Below
https://github.com/YOU/html-css-projects
Or direct link to index.html
Terminal Commands to Create & Push Day 38
1$
# 1. Enter your repository directory
2$
cd html-css-projects
Change working directory to html-css-projects
3$
# 2. Create the exact folder for Day 38
4$
mkdir day-38
Create a new project folder (day-38)
5$
cd day-38
Change working directory to day-38
6$
# 3. Create your code file: index.html
7$
# (Write your Day 38 homework code inside index.html)
8$
# 4. Save, stage, commit and push to GitHub:
9$
git add .
Stage all modified files and new assets for commit
10$
git commit -m "Day 38: Async/Await Syntax & Browser fetch() API Fundamentals"
Commit staged changes with a descriptive message
11$
git push origin main
Push local commits directly to your remote GitHub repository
⌨️ Paste into terminal:Ctrl + V✨ Word wrap active (no horizontal cutoff)
How to Avoid "Could not find your practical code file" Errors:
1.Use Lowercase index.html: Avoid spaces or custom names like Alan Turing..html or Index.HTML. Linux/GitHub servers are strictly case-sensitive.
2.Separate Day Folders: Create a new folder day-38/ for today so you don't overwrite previous days.
3.Ensure Public Visibility: If your GitHub repo is Private, automated validation cannot inspect your code. Set it to Public.
4.Check on GitHub Website: Before clicking "Verify", open your repo in Google Chrome to confirm your files were pushed to branch main.
📁 github.com/YOUR_USERNAME/html-css-projects
Branch: main
README.md# BCA Practical Portfolio overview
day-01/Day 1 Prior Lesson
└──index.html
day-02/Day 2 Prior Lesson
└──index.html
day-03/Day 3 Prior Lesson
└──index.html
day-04/Day 4 Prior Lesson
└──index.html
day-05/Day 5 Prior Lesson
└──index.html
day-06/Day 6 Prior Lesson
└──index.html
day-07/Day 7 Prior Lesson
└──index.html
day-08/Day 8 Prior Lesson
└──index.html
day-09/Day 9 Prior Lesson
└──index.html
day-10/Day 10 Prior Lesson
└──index.html
└──styles.css
day-11/Day 11 Prior Lesson
└──index.html
day-12/Day 12 Prior Lesson
└──index.html
day-13/Day 13 Prior Lesson
└──index.html
day-14/Day 14 Prior Lesson
└──index.html
day-15/Day 15 Prior Lesson
└──index.html
day-16/Day 16 Prior Lesson
└──index.html
day-17/Day 17 Prior Lesson
└──index.html
day-18/Day 18 Prior Lesson
└──index.html
day-19/Day 19 Prior Lesson
└──index.html
day-20/Day 20 Prior Lesson
└──index.html
└──styles.css
day-21/Day 21 Prior Lesson
└──index.html
day-22/Day 22 Prior Lesson
└──index.html
day-23/Day 23 Prior Lesson
└──index.html
day-24/Day 24 Prior Lesson
└──index.html
day-25/Day 25 Prior Lesson
└──index.html
day-26/Day 26 Prior Lesson
└──index.html
day-27/Day 27 Prior Lesson
└──index.html
day-28/Day 28 Prior Lesson
└──index.html
day-29/Day 29 Prior Lesson
└──index.html
day-30/Day 30 Prior Lesson
└──index.html
└──styles.css
day-31/Day 31 Prior Lesson
└──index.html
day-32/Day 32 Prior Lesson
└──index.html
day-33/Day 33 Prior Lesson
└──index.html
day-34/Day 34 Prior Lesson
└──index.html
day-35/Day 35 Prior Lesson
└──index.html
day-36/Day 36 Prior Lesson
└──index.html
day-37/Day 37 Prior Lesson
└──index.html
day-38/✨ CREATE THIS FOLDER FOR TODAY (Day 38)
└──index.htmlMust contain:
Sequential Progression Enforced

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
Day 37: Asynchronous JavaScript: Callbacks, Promises & Promise Chaining
WhatsApp
Curriculum & Practical Systems Authored by Er. Manoj Kumar
NextSem Academy • BCA Practical Learning Portal