📋 Table of Contents
async/অপেক্ষা কি?
Async/অপেক্ষাঅ্যাসিঙ্ক্রোনাস অপারেশনগুলির সাথে কাজ করার জন্য জাভাস্ক্রিপ্টের সবচেয়ে পরিষ্কার সিনট্যাক্স – নেটওয়ার্ক অনুরোধ, ফাইল I/O, ডাটাবেস প্রশ্ন, টাইমার। ES2017 (ES8) এ চালু করা হয়েছে, এটি অ্যাসিঙ্ক কোডকে সিঙ্ক্রোনাস কোডের মতো রিড করে:
async— অ্যাসিঙ্ক্রোনাস হিসাবে একটি ফাংশন চিহ্নিত করে; সর্বদা একটি প্রতিশ্রুতি ফিরিয়ে দেয়await— একটি প্রতিশ্রুতি স্থির না হওয়া পর্যন্ত একটি async ফাংশনের ভিতরে সম্পাদনকে বিরতি দেয়
await somePromiseসমতুল্যsomePromise.then(result => ...). একই প্রক্রিয়া, ক্লিনার সিনট্যাক্স।প্রথম প্রতিশ্রুতি: ফাউন্ডেশন
অ্যাসিঙ্ক/অপেক্ষা করার আগে, আপনি প্রতিশ্রুতির সাথে.then(). এটি বোঝার ফলে async/await ক্লিক করুন:
// Promise chain — works, but nests deeply
fetch('https://api.example.com/users/1')
.then(response => response.json())
.then(user => fetch('https://api.example.com/posts?userId=' + user.id))
.then(response => response.json())
.then(posts => console.log(posts))
.catch(error => console.error('Failed:', error));
// Same logic with async/await — flat and readable
async function getUserPosts(userId) {
const userRes = await fetch('https://api.example.com/users/' + userId);
const user = await userRes.json();
const postsRes = await fetch('https://api.example.com/posts?userId=' + user.id);
const posts = await postsRes.json();
return posts;
}
আপনার প্রথম অ্যাসিঙ্ক ফাংশন
async function getUser(id) {
const response = await fetch('https://jsonplaceholder.typicode.com/users/' + id);
if (!response.ok) throw new Error('HTTP error: ' + response.status);
return response.json();
}
const user = await getUser(1);
console.log(user.name); // "Leanne Graham"
মূল নিয়ম: একটিasyncফাংশন সর্বদা একটি প্রতিশ্রুতি প্রদান করে।awaitশুধুমাত্র অ্যাসিঙ্ক ফাংশনের ভিতরে কাজ করে। যদি একটি প্রতীক্ষিত প্রতিশ্রুতি প্রত্যাখ্যান করে, এটি একটি নিক্ষিপ্ত ত্রুটি হিসাবে প্রচার করে।
ট্রাই/ক্যাচ দিয়ে হ্যান্ডলিং ত্রুটি
async function fetchUserData(userId) {
try {
const response = await fetch('/api/users/' + userId);
if (!response.ok) throw new Error('Server error: ' + response.status);
return await response.json();
} catch (error) {
if (error.name === 'TypeError') {
console.error('Network error:', error.message);
} else {
console.error('API error:', error.message);
}
return null;
}
}
// Per-await error handling
async function loadDashboard() {
const user = await fetchUserData(1).catch(() => null);
const stats = await fetchStats().catch(() => ({ views: 0 }));
const alerts = await fetchAlerts().catch(() => []);
return { user, stats, alerts };
}
Promise.all() এর সাথে সমান্তরাল এক্সিকিউশন
অনুক্রমিক ওয়েট ওয়ান-এ-টাইম চালানো হয়। ব্যবহার করুনPromise.all()একই সাথে একাধিক প্রতিশ্রুতি বরখাস্ত করা:
// ❌ Sequential — 3 seconds total (1s + 1s + 1s)
async function loadSequential() {
const users = await fetchUsers(); // waits 1s
const posts = await fetchPosts(); // waits another 1s
const photos = await fetchPhotos(); // waits another 1s
return { users, posts, photos };
}
// ✅ Parallel — ~1 second total (all fire at once)
async function loadParallel() {
const [users, posts, photos] = await Promise.all([
fetchUsers(),
fetchPosts(),
fetchPhotos()
]);
return { users, posts, photos };
}
// Promise.allSettled — get results even if some fail
async function loadWithFallbacks() {
const results = await Promise.allSettled([fetchUsers(), fetchPosts(), fetchPhotos()]);
return results.map(r => r.status === 'fulfilled' ? r.value : null);
}
// Promise.race — first wins (timeout pattern)
async function fetchWithTimeout(url, ms = 5000) {
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Request timed out')), ms)
);
return Promise.race([fetch(url), timeout]);
}
Async লুপস: সঠিক পথ
const userIds = [1, 2, 3, 4, 5];
// ❌ forEach DOES NOT await — requests fire but nothing waits
userIds.forEach(async (id) => {
const user = await fetchUser(id); // fires immediately without waiting
console.log(user.name);
});
// ✅ for...of — sequential (each awaits before next starts)
for (const id of userIds) {
const user = await fetchUser(id);
console.log(user.name);
}
// ✅ Promise.all + map — parallel (all fire simultaneously)
const users = await Promise.all(userIds.map(id => fetchUser(id)));
users.forEach(u => console.log(u.name));
// ✅ Batched parallel (avoid overwhelming the server)
async function batchProcess(ids, batchSize = 5) {
const results = [];
for (let i = 0; i < ids.length; i += batchSize) {
const batch = ids.slice(i, i + batchSize);
const batchResults = await Promise.all(batch.map(id => fetchUser(id)));
results.push(...batchResults);
}
return results;
}
উন্নত প্যাটার্নস
Async IIFE
// Async IIFE — top-level await not available? Use this
(async () => {
const config = await loadConfig();
await startServer(config);
console.log('Server running on port', config.port);
})();
Async জেনারেটর (স্ট্রিমিং)
async function* streamLargeDataset(url) {
let page = 1;
while (true) {
const response = await fetch(url + '?page=' + page);
const data = await response.json();
if (!data.items.length) break;
yield data.items;
page++;
}
}
// Consume with for-await-of
for await (const items of streamLargeDataset('/api/records')) {
processItems(items);
}
এক্সপোনেনশিয়াল ব্যাকঅফের সাথে পুনরায় চেষ্টা করুন
async function fetchWithRetry(url, options = {}, retries = 3, backoff = 1000) {
try {
const res = await fetch(url, options);
if (!res.ok && res.status >= 500 && retries > 0) {
await new Promise(r => setTimeout(r, backoff));
return fetchWithRetry(url, options, retries - 1, backoff * 2);
}
return res;
} catch (err) {
if (retries > 0) {
await new Promise(r => setTimeout(r, backoff));
return fetchWithRetry(url, options, retries - 1, backoff * 2);
}
throw err;
}
}
সাধারণ ভুল
- ভুলে যাওয়া
await– আপনি একটি মুলতুবি প্রতিশ্রুতি পাবেন, একটি মূল্য নয় - প্রতিটির জন্য async— ব্যবহার করুন
for...ofঅথবাPromise.allপরিবর্তে - অনুক্রমিক অপেক্ষা করছে যখন সমান্তরাল সম্ভব— অপ্রয়োজনীয় সিরিয়ালাইজেশন পারফরম্যান্সকে হত্যা করে
- গিলে ফেলা ত্রুটিগুলি– খালি ক্যাচ ব্লক বাগ লুকিয়ে রাখে। লগ বা রিথ্রো.
// ❌ Missing await — user is a Promise, not an object
async function broken() {
const user = fetchUser(1); // missing await!
console.log(user.name); // undefined — user is a Promise
}
// ✅ Fixed
async function fixed() {
const user = await fetchUser(1);
console.log(user.name); // "Leanne Graham"
}
রিয়েল-ওয়ার্ল্ড API প্যাটার্ন
টাইমআউট এবং ত্রুটি পরিচালনা সহ একটি উত্পাদন-প্রস্তুত API ক্লায়েন্ট:
class ApiClient {
constructor(baseUrl, options = {}) {
this.baseUrl = baseUrl;
this.timeout = options.timeout || 10000;
}
async request(path, options = {}) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
try {
const response = await fetch(this.baseUrl + path, {
...options,
signal: controller.signal,
headers: { 'Content-Type': 'application/json', ...options.headers }
});
clearTimeout(timeoutId);
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw Object.assign(new Error(err.message || 'HTTP ' + response.status), {
status: response.status, body: err
});
}
return response.json();
} catch (error) {
clearTimeout(timeoutId);
if (error.name === 'AbortError') throw new Error('Request timed out');
throw error;
}
}
async get(path) { return this.request(path); }
async post(path, body) { return this.request(path, { method: 'POST', body: JSON.stringify(body) }); }
}
const api = new ApiClient('https://api.example.com', { timeout: 8000 });
const user = await api.get('/users/1');
🚀 আপনার জাভাস্ক্রিপ্ট লেভেল আপ করুন
Async/await হল অন্যতম গুরুত্বপূর্ণ আধুনিক JS প্যাটার্ন। এক্সপ্লোর করুনকেন TypeScript অ্যাসিঙ্ক প্যাটার্নগুলিকে আরও নিরাপদ করে তোলে ||||৷ , অথবা চেকসমস্ত প্রোগ্রামিং গাইডআরও গভীর ডাইভের জন্য।প্রায়শই জিজ্ঞাসিত প্রশ্ন
async/অপেক্ষা কি?
প্রতিশ্রুতি উপর সিনট্যাকটিক চিনি.
একটি ফাংশন অ্যাসিঙ্ক চিহ্নিত করে;asyncএকটি প্রতিশ্রুতি নিষ্পত্তি না হওয়া পর্যন্ত এটি বিরতি. অ্যাসিঙ্ক কোড সিঙ্ক কোডের মতো রিড করে।awaitঅ্যাসিঙ্ক/অপেক্ষা এবং প্রতিশ্রুতির মধ্যে পার্থক্য?
একই প্রক্রিয়া, ক্লিনার সিনট্যাক্স। পঠনযোগ্যতার জন্য async/await ব্যবহার করুন; জন্য কাঁচা প্রতিশ্রুতি ব্যবহার করুন
,Promise.all().Promise.race()কিভাবে ত্রুটি পরিচালনা করতে?
ট্রাই/ক্যাচ ব্লক ব্যবহার করুন। অথবা যোগ করুন
পৃথক প্রতীক্ষিত প্রতিশ্রুতি..catch()কিভাবে সমান্তরাল অপারেশন চালানো?
— একযোগে সব আগুন।
await Promise.all([p1, p2, p3])forEach এ async/অপেক্ষা করবেন?
না — প্রতিটি অ্যাসিঙ্ক কলব্যাক উপেক্ষা করে। ব্যবহার করুন
অথবাfor...of.Promise.all(arr.map(async x => ...))শীর্ষ স্তরের অপেক্ষা কি?
ES2022 — অ্যাসিঙ্ক র্যাপার ছাড়াই মডিউল টপ লেভেলে ওয়েট ব্যবহার করুন। শুধুমাত্র ES মডিউল।
ES2022 — use await at module top level without async wrapper. ES modules only.
🔗 Share this article
✍️ Leave a Comment