📋 Table of Contents
ما هو المزامنة/الانتظار؟
غير متزامن/انتظارهو أنظف بناء جملة لـ JavaScript للعمل مع العمليات غير المتزامنة – طلبات الشبكة، وإدخال/إخراج الملفات، واستعلامات قاعدة البيانات، والمؤقتات. تم تقديمه في ES2017 (ES8)، وهو يجعل التعليمات البرمجية غير المتزامنة تُقرأ مثل التعليمات البرمجية المتزامنة:
async— وضع علامة على دالة على أنها غير متزامنة؛ يُرجع دائمًا وعدًاawait— يوقف التنفيذ مؤقتًا داخل دالة غير متزامنة حتى يستقر الوعد
await somePromiseيعادلsomePromise.then(result => ...). نفس الآلية، بناء الجملة الأنظف.الوعود أولاً: المؤسسة
قبل عدم المزامنة/الانتظار، قمت بربط الوعود بـ.then(). فهم هذا يجعل النقر غير المتزامن/الانتظار:
// 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]);
}
الحلقات غير المتزامنة: الطريق الصحيح
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;
}
الأنماط المتقدمة
غير متزامن 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 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— تحصل على وعد معلق، وليس قيمة - غير متزامن في forEach– استخدم
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 جاهز للإنتاج مع انتهاء المهلة ومعالجة الأخطاء:
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يمثل وظيفة غير متزامنة؛awaitيوقفه مؤقتًا حتى يستقر الوعد. يجعل رمز المزامنة يُقرأ مثل رمز المزامنة.
الفرق بين المزامنة/الانتظار والوعود؟
نفس الآلية، بناء الجملة الأنظف. استخدم المزامنة/الانتظار لسهولة القراءة؛ استخدم الوعود الأولية لـPromise.all(),Promise.race().
كيفية التعامل مع الأخطاء؟
استخدم كتل المحاولة/الالتقاط. أو إلحاق.catch()للوعود الفردية المنتظرة.
كيفية تشغيل العمليات بالتوازي؟
await Promise.all([p1, p2, p3])– الحرائق في وقت واحد.
غير متزامن/في انتظار forEach؟
لا – يتجاهل forEach عمليات الاسترجاعات غير المتزامنة. استخدمfor...ofأوPromise.all(arr.map(async x => ...)).
ما هو المستوى الأعلى الذي ينتظره؟
ES2022 – استخدم الانتظار في المستوى الأعلى للوحدة بدون غلاف غير متزامن. وحدات ES فقط.
🔗 Share this article
✍️ Leave a Comment