async · await

Use async to declare a function that returns a Promise. Inside it, use await to pause until a Promise settles and extract its value.
try/catch/finally works with await for error handling and cleanup.


Syntax

// Declare
async function load(url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error("Bad response");
  return await res.text();
}

// Arrow
const loadJSON = async (url) => {
  const res = await fetch(url);
  return await res.json();
};

Examples

// ১) সিকোয়েন্সিয়াল — একটার পর একটা
অসমলয় ফাংশন ডেটাআনো() {
  চেষ্টা {
    const a = অপেক্ষা fetch("/a");
    const b = অপেক্ষা fetch("/b"); // /a শেষ না হলে শুরু হবে না
    const c = অপেক্ষা fetch("/c");
    ফেরত [অপেক্ষা a.text(), অপেক্ষা b.text(), অপেক্ষা c.text()];
  } ধরুন (ত্রু) {
    কনসোল.ত্রুটি("লোড ব্যর্থ:", ত্রু.message);
    ফেরত [];
  } অবশেষে {
    কনসোল.তথ্য("শেষ");
  }
}

// ২) প্যারালাল — Promise.all দিয়ে
অসমলয় ফাংশন দ্রুতআনো() {
  চেষ্টা {
    const [a, b, c] = অপেক্ষা Promise.all([
      fetch("/a"),
      fetch("/b"),
      fetch("/c"),
    ]);
    ফেরত অপেক্ষা Promise.all([a.text(), b.text(), c.text()]);
  } ধরুন (ত্রু) {
    কনসোল.ত্রুটি("ব্যর্থ:", ত্রু);
    ফেরত [];
  }
}

// ৩) for‑await‑of — স্ট্রিম/অ্যাসিঙ্ক ইটারেবল
অসমলয় ফাংশন পড়ো(স্ট্রিম) {
  চেষ্টা {
    জন্য অপেক্ষা (const চাঙ্ক এর স্ট্রিম) {     // for await...of
      কনসোল.লগ("চাঙ্ক:", চাঙ্ক);
    }
  } অবশেষে {
    কনসোল.তথ্য("স্ট্রিম বন্ধ");
  }
}

// ৪) টপ‑লেভেল অপেক্ষা (ES মডিউলে)
// const config = অপেক্ষা fetch("/cfg.json").then(r => r.json());

Notes

  • await serializes by default; to run tasks in parallel, start promises first, then await them (or use Promise.all).
  • Wrap await in try/catch to handle rejections. finally runs for cleanup.
  • Avoid await inside hot for loops when tasks are independent — batch them and Promise.all.
  • for await...of works on async iterables (streams, readers).
  • Top‑level await is allowed only in ES modules.
  • Keep one language style (English/Bangla/Banglish) per file for consistency.