Guest Mode:

BCA Student Stories & UpdatesLive

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

Asynchronous JavaScript: Callbacks, Promises & Promise Chaining

Real-world software is inherently asynchronous: fetching data from a database, uploading an image, or reading disk files takes time. Promises represent a value that may not be available right now, but will resolve in the future or fail gracefully with an error.

Interactive Learning Roadmap

Day 37 Step-by-Step Practical Flow

🎯1. What You Will Learn Today

✔Understand synchronous blocking vs asynchronous non-blocking programming models.
✔Identify the Callback Hell pyramid of doom and understand why Promises were introduced in ES6.
✔Create custom Promise instances using new Promise((resolve, reject) => ...).
✔Chain asynchronous steps cleanly using .then(), catch errors with .catch(), and clean up with .finally().
✔Simulate multi-step server workflows (Authentication -> Data Fetch -> Record Update).
Day 37 MasterclassAdvanced JavaScript & Browser APIs

Asynchronous JavaScript: Callbacks, Promises & Promise Chaining — Comprehensive Practical Guide

Har concept ko visual mental models, code anatomy aur practical industry tips ke sath samjhein.

Real-World Purpose Aur Zaroorat

Real-world software is inherently asynchronous: fetching data from a database, uploading an image, or reading disk files takes time. Promises represent a value that may not be available right now, but will resolve in the future or fail gracefully with an error.

Three Promise States: Pending (in progress), Fulfilled (successful with resolve), Rejected (failed with reject).
Chaining: Every .then() returns a new Promise, allowing linear sequential chaining without nested callbacks.
Unified Error Handling: A single .catch() at the end of the chain handles errors thrown by any preceding step.
.finally(): Executes unconditionally regardless of whether the Promise was fulfilled or rejected (great for turning off loading spinners).
Promise.all(): Runs multiple promises in parallel and resolves when all have completed.
Dimaag Mein Bithane Ka Model

"Think of a Promise like ordering food at a university canteen: the cashier gives you a token (Promise: Pending). You sit at your table and study. When your order is ready, the buzzer sounds (Fulfilled: resolve), or if an item is out of stock, they inform you (Rejected: reject)."

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

👨‍🏫3. Teacher Demonstration Code

Notice how three asynchronous steps execute in sequence with clean chaining and centralized error catching.

Multi-Step University Record Pipeline with Promiseshtml
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: 'Segoe UI', sans-serif; background: #060c18; color: #fff; padding: 24px; }
    .card { max-width: 480px; margin: auto; background: #0c1328; border: 1px solid #1e293b; padding: 24px; border-radius: 12px; }
    button { padding: 12px 20px; background: #2563eb; color: #fff; border: none; border-radius: 6px; font-weight: bold; cursor: pointer; }
    .log-box { margin-top: 16px; padding: 14px; background: #060c18; border: 1px solid #334155; border-radius: 6px; min-height: 120px; font-family: monospace; font-size: 13px; }
    .step { color: #38bdf8; margin: 4px 0; }
    .success { color: #10b981; }
    .error { color: #ef4444; }
  </style>
</head>
<body>
  <div class="card">
    <h3>⚡ Asynchronous Record Verification</h3>
    <button id="runBtn">Start Verification Pipeline</button>
    <div class="log-box" id="logs">Click button to start...</div>
  </div>

  <script>
    const logs = document.getElementById("logs");
    const runBtn = document.getElementById("runBtn");

    function log(msg, cls = "step") {
      const p = document.createElement("div");
      p.className = cls;
      p.textContent = "[" + new Date().toLocaleTimeString() + "] " + msg;
      logs.appendChild(p);
    }

    // Step 1: Simulate Authentication
    function authenticateStudent(id) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          if (id === 2401) resolve({ id: 2401, name: "Rahul Sharma", token: "AUTH_TOKEN_BCA" });
          else reject(new Error("Student ID not found in registry"));
        }, 800);
      });
    }

    // Step 2: Fetch Grades
    function fetchGrades(token) {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ token, bcs011: 85, bcsl013: 92, sgpa: 8.8 });
        }, 1000);
      });
    }

    runBtn.addEventListener("click", () => {
      logs.innerHTML = "";
      runBtn.disabled = true;
      log("Initiating pipeline...");

      authenticateStudent(2401)
        .then((user) => {
          log("✓ Step 1: Authenticated student " + user.name);
          return fetchGrades(user.token);
        })
        .then((grades) => {
          log("✓ Step 2: Grades fetched successfully. SGPA: " + grades.sgpa, "success");
          log("🎉 Pipeline Complete: Eligible for Semester 2 enrollment!", "success");
        })
        .catch((err) => {
          log("✖ Error: " + err.message, "error");
        })
        .finally(() => {
          runBtn.disabled = false;
        });
    });
  </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 37 Practical Task Test Studio

Test Score:0 / 2 Passed
1. Practical Task Specifications & Live Test Checklist:Type code below to pass tests
Task 1Instantiate Promise with Resolve/Reject

Create a function returning new Promise((resolve, reject) => { setTimeout(...) }).

⏳ WAITING
Task 2Chain with .then() and .catch()

Invoke the promise function and attach .then() for success and .catch() for error handling.

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

The Missing Return in Promise Chain Bug

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

Click any code line
⚠️ Broken Code Inspector
Tap buggy line
1
fetchStudent(101)
2
.then((student) => {
3
// ❌ Bug: Forgot to 'return' the next promise!
4
fetchTranscript(student.id);
5
})
6
.then((transcript) => {
7
// transcript is UNDEFINED because previous .then() returned nothing!
8
console.log("CGPA:", transcript.cgpa); // TypeError: Cannot read properties of undefined
9
});
Stuck? Need a detective clue before checking the solution?

Senior Developer Forensic Analysis:

Inside a .then() handler, if you do not explicitly return a Promise or value, the handler implicitly returns undefined. The next .then() in the chain immediately receives undefined rather than waiting for the inner asynchronous operation to resolve.

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

📝Independent Practice: Assignment

📄 index.html

BCA Cloud Deployment Simulator with Promise Steps

  • •Build a multi-step simulated deployment pipeline with 3 async steps: 1. Code Linting (800ms), 2. Test Suite (1000ms), 3. Server Deployment (1200ms).
  • •Display an animated progress bar and step-by-step console logs.
  • •Randomly simulate a 20% test failure chance to demonstrate clean .catch() error recovery.
  • •Always re-enable the deploy button using .finally().
Submission Evaluation Criteria: Push index.html and deploySimulator.js to GitHub under day-37.
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 37 - Promise Pipeline</title>
  <style>
    body { font-family: 'Segoe UI', monospace; background: #060c18; color: #fff; padding: 24px; }
    .card { max-width: 500px; margin: auto; background: #0c1328; border: 1px solid #1e293b; padding: 24px; border-radius: 12px; }
    button { padding: 12px 20px; background: #2563eb; color: #fff; border: none; border-radius: 6px; font-weight: bold; cursor: pointer; }
    button:disabled { background: #334155; cursor: not-allowed; }
    .terminal { margin-top: 16px; background: #060c18; border: 1px solid #334155; padding: 14px; border-radius: 8px; min-height: 140px; font-size: 13px; }
    .ok { color: #10b981; }
    .err { color: #ef4444; }
  </style>
</head>
<body>
  <div class="card">
    <h2>🚀 NextSem Cloud Deployer</h2>
    <button id="deployBtn">Deploy BCA Portal</button>
    <div class="terminal" id="termLogs">System idle. Ready to deploy.</div>
  </div>

  <script>
    const btn = document.getElementById("deployBtn");
    const term = document.getElementById("termLogs");

    function log(msg, cls = "") {
      const line = document.createElement("div");
      if (cls) line.className = cls;
      line.textContent = "> " + msg;
      term.appendChild(line);
    }

    function step(name, ms, failChance = 0) {
      return new Promise((resolve, reject) => {
        log("Running " + name + "...");
        setTimeout(() => {
          if (Math.random() < failChance) reject(new Error(name + " failed"));
          else resolve("✓ " + name + " passed");
        }, ms);
      });
    }

    btn.addEventListener("click", () => {
      btn.disabled = true;
      term.innerHTML = "";
      log("Starting build pipeline...");

      step("ESLint Code Check", 800)
        .then((res) => {
          log(res, "ok");
          return step("Unit Test Suite", 1000, 0.2); // 20% fail chance
        })
        .then((res) => {
          log(res, "ok");
          return step("Production CDN Deployment", 1200);
        })
        .then((res) => {
          log(res, "ok");
          log("🎉 Application Deployed to https://nextsem-academy.web.app", "ok");
        })
        .catch((err) => {
          log("🚨 DEPLOYMENT HALTED: " + err.message, "err");
        })
        .finally(() => {
          btn.disabled = false;
        });
    });
  </script>
</body>
</html>
Verified Assignment Code Solution (100% Tested & Ready to Run)

🎓4. Viva Check: Mandatory Conceptual Test

What happens if you omit the return statement when calling a Promise-returning function inside a .then() block?

5. Mandatory Step: Push to GitHub to Unlock Next Lesson

Target Repo: html-css-projects

Windows 11 Terminal / VS Code
1$
mkdir day-37
Create a new project folder (day-37)
2$
cd day-37
Change working directory to day-37
3$
git checkout -b feature/day-37-promises
4$
git add index.html
5$
git commit -m "feat(day-37): implement asynchronous javascript promises and pipeline chaining"
Commit staged changes with a descriptive message
6$
git push origin feature/day-37-promises
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 37 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-37/ or bca-day-37/
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 37
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 37
4$
mkdir day-37
Create a new project folder (day-37)
5$
cd day-37
Change working directory to day-37
6$
# 3. Create your code file: index.html
7$
# (Write your Day 37 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 37: Asynchronous JavaScript: Callbacks, Promises & Promise Chaining"
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-37/ 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/✨ CREATE THIS FOLDER FOR TODAY (Day 37)
└──index.htmlMust contain:
Sequential Progression Enforced

You are welcome to read all notes, inspect code snippets, and practice all exercises of Day 37 freely! To officially submit your GitHub repository and unlock subsequent days in your portfolio, please complete Day 36: Client-Side Form Validation & Real-Time Regex Diagnostics first.

Complete Day 36 First
Day 36: Client-Side Form Validation & Real-Time Regex Diagnostics
WhatsApp
Curriculum & Practical Systems Authored by Er. Manoj Kumar
NextSem Academy • BCA Practical Learning Portal