Friday, August 29, 2025

Javascript Module 58

  Module 58 : Working with Async. 

1. What is Asynchronous Programming?

JavaScript is single-threaded, meaning it can execute only one operation at a time. But it supports non-blocking asynchronous operations, such as:








Fetching data from an API

Reading files

Timers (setTimeout, setInterval)

Event listeners

This allows faster execution and responsive applications.


 2. Understanding the Core Concepts

2.1 ✅ Callbacks

A callback is a function passed as an argument to another function and executed after an operation is completed.

function getData(callback) { setTimeout(() => { callback("Data received!"); }, 2000); } getData(function(message) { console.log(message); // Output: Data received! });

Problem: Callback Hell — nesting too many callbacks makes code messy and hard to debug.


2.2 📦 Promises

A Promise represents a value that may be available now, later, or never.

const fetchData = () => { return new Promise((resolve, reject) => { setTimeout(() => { const success = true; success ? resolve("Data Loaded") : reject("Error Occurred"); }, 2000); }); }; fetchData() .then(data => console.log(data)) .catch(error => console.error(error));

 resolve() is called when the async operation is successful, reject() when there is an error.


2.3 🔁 async/await (Modern Syntax)

async/await is syntactic sugar over promises. It makes async code look synchronous, improving readability.

















async function loadData() { try { const response = await fetchData(); // waits for promise to resolve console.log(response); } catch (error) { console.error(error); } } loadData();

Much easier to read, handle, and maintain compared to .then() chaining.


 3. Examples

Example 1: Simulate API Call


function fakeAPI(endpoint) { return new Promise((resolve) => { setTimeout(() => { resolve(`Data from ${endpoint}`); }, 1500); }); } async function getMultipleData() { const data1 = await fakeAPI("/user"); const data2 = await fakeAPI("/posts"); console.log(data1); console.log(data2); } getMultipleData();

Example 2: Error Handling with Async

function unreliableAPI() { return new Promise((resolve, reject) => { const success = Math.random() > 0.5; setTimeout(() => { success ? resolve("Success!") : reject("Failed!"); }, 1000); }); } async function fetchData() { try { const result = await unreliableAPI(); console.log(result); } catch (error) { console.error("Caught an error:", error); } } fetchData();


 4. Exercises

 Exercise 1: Write a function delayPrint(msg, delay) that prints a message after a delay.











function delayPrint(msg, delay) { return new Promise((resolve) => { setTimeout(() => { console.log(msg); resolve(); }, delay); }); } // Usage async function run() { await delayPrint("Hello", 1000); await delayPrint("Async", 1000); await delayPrint("World!", 1000); } run();

 This chaining multiple async tasks in order using await.


Exercise 2: Fetch data using fetch() from a public API

async function fetchUser() { try { const response = await fetch("https://jsonplaceholder.typicode.com/users/1"); const user = await response.json(); console.log(user.name); } catch (error) { console.error("Error fetching user:", error); } } fetchUser();



  API interaction.


Guidance

Use animation/diagram to explain call stack, Web APIs, callback queue, and event loop.

Compare synchronous vs asynchronous execution with examples.

 code callback, promise, and async/await examples.

Show how callback hell can be avoided using promises and async/await.

Guided 

Ask them to write a getWeather(city) function that fetches weather data from an API.

          Debugging Tips

Why is my function returning undefined? (Explain awaiting the result.)

How to catch multiple errors across nested async calls?

When to use Promise.all()?


 6. Research Insights (Coding Specialist’s View)








Concept

Best Practice

Reason

Async/Await

Always wrap in try/catch

Prevents crashing due to uncaught errors

Promises

Use chaining .then() only when simple

Improves readability in small scenarios

API Calls

Use async/await for better structure

Easier to debug and maintain

Performance

Use Promise.all() when parallel calls are possible

Speeds up execution

UX

Add loading indicators while awaiting

Better user experience


👨‍💻 Coding Insight: Mixing async/await and .then() can lead to confusion. Stick to one style per function.


 Tip : Using Promise.all()

async function fetchMultiple() { const [user, posts] = await Promise.all([ fetch("https://jsonplaceholder.typicode.com/users/1").then(res => res.json()), fetch("https://jsonplaceholder.typicode.com/posts/1").then(res => res.json()) ]); console.log("User:", user.name); console.log("Post Title:", posts.title); }

 Great for optimizing multiple independent API requests.


  Summary

Concept

Purpose

Syntax Style

Callback

Run function after completion

callback()

Promise

Manage success/failure

.then().catch()

Async/Await

Clean, readable async code

async function, await keyword


 Module Files (Optional for Distribution)




async-demo.html – HTML with embedded JS examples

async-exercises.js – Exercises with solutions

async-project.js – Mini project (fetch API + UI)



No comments:

Post a Comment

Javascript Module 78

  Javascript   Module 78 If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test...