Asynchronous JS

async/await

Promises Ko Aur Bhi Clean Banana
💡 async/await Promises ko "synchronous-jaisa DIKHNE" wala syntax deta hai — jaise ek recipe ko step-by-step padhna (await = "yaha ruk kar wait karo"), chahe underneath asal mein async operations chal rahe hon.

async keyword function ko "Promise-returning" bana deta hai. await keyword (sirf async function ke ANDAR use ho sakta hai) ek Promise ke resolve hone ka wait karta hai, AUR uska result seedha return karta hai — jaise sync code, lekin actually async hai underneath. try/catch se errors handle karte hain (.catch() ki jagah).

function fetchUserData(id) {
  return new Promise((resolve) => {
    setTimeout(() => resolve({ id: id, name: "Aarav" }), 1000);
  });
}

async function getUser() {
  try {
    const user = await fetchUserData(1);   // Promise resolve hone ka wait
    console.log("User mila: " + user.name);
    return user;
  } catch (error) {
    console.log("Error: " + error);
  }
}

getUser();

// Multiple awaits, sequential aur readable:
async function getFullData() {
  const user = await fetchUserData(1);
  const posts = await fetchPosts(user.id);   // pichle await ke baad hi chalta hai
  console.log(posts);
}
async/await Promises ko "synchronous-jaisa DIKHNE" wala syntax deta hai — jaise ek recipe ko step-by-step padhna (await = "yaha ruk kar wait karo"), chahe underneath asal mein async operations chal rahe hon.
1 / 6
⚡ Quick Recap
  • async function = Promise return karta hai automatically
  • await = Promise resolve hone ka wait, result seedha milta hai
  • try/catch = errors handle karna, .catch() ki jagah
On this page (2 subtopics)

await ko sequentially likhna (ek ke baad ek) SLOW ho sakta hai agar operations independent hain — Promise.all() ke saath combine karke parallel execution achieve karo.

// SLOW — sequential (total time = sum):
async function slow() {
  const a = await fetchA();   // 1 second
  const b = await fetchB();   // 1 second
  // Total: 2 seconds
}

// FAST — parallel (total time = max):
async function fast() {
  const [a, b] = await Promise.all([fetchA(), fetchB()]);
  // Total: 1 second (dono ek saath chal rahe hain)
}
⚠️Common Mistake: Agar operations INDEPENDENT hain (ek doosre par depend nahi karte), unhe sequentially await karna unnecessary slow hai — Promise.all() se parallel chalाओ. Sirf tab sequential await karo jab genuinely ek result doosre ke liye zaroori ho.

Modern JavaScript (ES modules) mein await async function ke BAHAR bhi, module ke top-level par directly use ho sakta hai — pehle IIFE wrap karna padta tha, ab zaroorat nahi.

// Modern module (type="module"):
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
// Koi wrapping async function ki zaroorat nahi!
💡Tip: Top-level await sirf ES modules mein kaam karta hai (script type="module"), regular scripts mein nahi — aur sirf module-level code mein, kisi function ke andar nahi (wahan normal async function chahiye).