M E R N S TA C K — N O D E .
J S F O U N D AT I O N
Module 4: Async JavaScript + Event Loop
Callbacks, Promises, async/await — aur Node ke andar-andar
ye sab kaam kaise karta hai, poori tarah samajhte hain.
Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327
ROADMAP
Is Module Mein Kya Kya Cover Hoga
1 2
Callbacks aur 'Callback Hell' Promises — states, .then/.catch
3 4
async/await — Promises ka clean syntax [Link] — parallel mein kaam karna
5 6
Event Loop — Node ke andar ka jaadu Real-world pipeline + common mistakes
Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 2
QUICK RECAP
Module 3 Se Yaad Hai?
• fs module mein humne dekha — readFile (async, callback ke saath) vs readFileSync (blocking).
• fs/promises se async/await bhi ek jhalak dekhi thi.
• Par 'async kaam karta kaise hai' — ye abhi poori tarah nahi samjha.
• Ye module [Link] ka sabse important concept hai — isके bina backend development mushkil hai. Dhyan se!
Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 3
RECAP
Callback — Ek Function, Doosre Ko Diya Hua
Ye concept naya nahi hai — React mein onClick={fn} bhi ek callback hai. Node mein bhi wahi pattern.
[Link]('[Link]', 'utf8', (err, data) => {
[Link](data)
})
// (err, data) => {...} — yehi callback hai.
// 'Jab file padh li jaaye, YE function chalao'
Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 4
THE PROBLEM
Callback Hell — Jab Callbacks Nest Ho Jaayein
Agar ek async kaam doosre pe depend kare, aur wo teesre pe — callbacks ke andar callbacks aane lagte hain.
getStudent(id, (student) => {
getCourse([Link], (course) => {
getInstructor([Link], (instructor) => {
[Link]([Link])
// aur nested hota jaaye...
})
})
})
// Isko 'Pyramid of Doom' bhi kehte hain — padhna,
// debug karna, error handle karna — sab mushkil
Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 5
THE FIX
Promises — Ek Better Tarika
Promise ek object hai jo ek future value ka 'waada' (promise) karta hai — abhi value nahi hai, par aa jayegi (ya fail ho jayega).
Simple Analogy
Socho tumne Zomato pe order kiya. Order place hote hi khana turant nahi milta — par tumhe ek 'order confirmed' message milta
hai (ek promise!).
Aage jaake ya to khana aayega ( ✔ resolved/fulfilled), ya order cancel ho jayega (✘ rejected). Tab tak order 'pending' hai.
Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 6
SYNTAX
Promise States + .then() / .catch()
Pending Fulfilled ✔ Rejected ✘
Abhi result nahi aaya Kaam successful hua Kaam fail hua
fetchStudent(id)
.then((student) => {
[Link]([Link]) // resolved ho gaya
})
.catch((err) => {
[Link](err) // rejected ho gaya
})
Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 7
HANDS-ON
Apna Khud Ka Promise Banana
Real projects mein aksar libraries (jaise mongoose) already Promises deti hain — par samajhne ke liye khud banana zaroori hai.
function fetchStudent(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id) {
resolve({ id, name: "Ananya" })
} else {
reject("Student not found")
}
}, 1000) // jaise ek database call ka delay
})
}
Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 8
THE CLEAN WAY
async/await — Promises Ko Padhna Aasan
async/await, Promises ke UPAR hi bana hua syntax hai — bas dikhta 'synchronous' jaisa hai, padhne mein aasan.
.then() Wala Tarika async/await Wala Tarika ✔
function getStudentName(id) { async function getStudentName(id) {
fetchStudent(id) const s = await fetchStudent(id)
.then((s) => { [Link]([Link])
[Link]([Link]) }
})
}
await sirf async function ke ANDAR chalta hai. Ye Node ko 'yahan ruko, result aane do, phir aage badho' batata hai — bina baaki server ko block kiye.
Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 9
ERROR HANDLING
async Functions Mein try/catch
.catch() ki jagah, async/await ke saath normal try/catch use karte hain.
async function getStudentName(id) {
try {
const s = await fetchStudent(id)
[Link]([Link])
} catch (error) {
[Link]("Kuch galat hua:", error)
}
}
// agar fetchStudent() reject ho, catch block
// pakad lega — poora app crash nahi hoga
Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 10
PARALLEL KAAM
[Link] — Ek Saath, Sabka Wait
Agar 3 alag-alag async kaam ek dusre pe depend nahi karte, unhe ek saath (parallel) chalao — sequential se kaafi fast.
async function getAllData() {
const [students, courses, instructors] = await [Link]([
fetchStudents(),
fetchCourses(),
fetchInstructors()
])
[Link](students, courses, instructors)
}
// teeno EK SAATH shuru hote hain, jab sab
// khatam ho jaayein, tabhi aage badhta hai
Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 11
REAL WORLD
Sequential vs Parallel — Farak Dekho
Socho har fetch call 1 second leti hai:
❌ Sequential (await, await, await) — 3 seconds
const students = await fetchStudents() // 1 sec wait
const courses = await fetchCourses() // +1 sec wait
const instructors = await fetchInstructors() // +1 sec wait
✔ Parallel ([Link]) — sirf 1 second
const [students, courses, instructors] = await [Link]([...])
// teeno saath shuru — sabse dheeme wale jitna hi time
Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 12
ANDAR KA JAADU
The Event Loop — Ye Sab Kaam Kaise Karta Hai
Node single-threaded hai (ek waqt mein ek hi kaam kar sakta hai) — phir bhi bina block kiye hazaron requests kaise handle karta hai?
1
Call Stack — Normal, synchronous code yahan chalta hai — ek ke baad ek
2
Async Kaam (fs, network, timer) — Node ye kaam 'background' (libuv) ko de deta hai, khud aage badh jaata hai
3
Callback Queue — Jab background kaam poora ho jaaye, uska callback yahan 'line mein lag' jaata hai
4
Event Loop — Jab Call Stack khaali ho, Event Loop queue se agla callback utha ke chala deta hai
Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 13
PUT IT TOGETHER
Real Example — Async Data Pipeline
fs/promises (Module 3) + async/await + try/catch — sab ek saath.
const fs = require('fs/promises')
async function addStudent(newStudent) {
try {
const raw = await [Link]('[Link]', 'utf8')
const students = [Link](raw)
[Link](newStudent)
await [Link]('[Link]', [Link](students, null, 2))
[Link]("Student added!")
} catch (err) {
[Link]("Failed:", err)
}
}
Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 14
WATCH OUT
Common Async Mistakes
✕
await likhna bhool jaana
Fix: bina await ke tumhe Promise object milega, asal value nahi
✕
async function ke bahar await use karna
Fix: await sirf async function ke andar chalta hai
✕
Independent kaamon ko sequential await se karna
Fix: agar ek dusre pe depend nahi karte, [Link] use karo — fast hoga
✕
.catch() ya try/catch bhool jaana
Fix: har async operation fail ho sakta hai — hamesha error handle karo
Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 15
WRAP UP
Quick Recap + Practice Task
• Callbacks kaam karte hain, par nested ho to 'callback hell' banta hai
• Promise = future value ka waada — pending/fulfilled/rejected 🎯 PRACTICE TASK
• async/await Promises ko synchronous jaisa dikhata hai
• try/catch se async errors handle karo
1. Ek Promise banao jo 2 second baad ek naam resolve kare
• [Link] se independent kaam parallel mein karo
• Event Loop hi Node ko non-blocking banata hai
2. Usko async/await se use karo, [Link] karo
3. Module 3 wale [Link] ko async/await + fs/promises
se rewrite karo
4. Bonus: 3 alag setTimeout-based promises banao aur
[Link] se ek saath chalao
Next Module → HTTP Server From Scratch
Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 16
Shukriya!
Questions? Doubts? Comment ya class mein poocho.
Agle module mein milte hain — HTTP Server From Scratch ke saath.
YC OT E S C O M P U T E R C L A S S E S