شغّل هذا البرنامج وانظر جيداً إلى ترتيب المخرجات:
console.log("1. تم الطلب");
setTimeout(() => {
console.log("3. وصل الطعام!");
}, 1000);
console.log("2. أقرأ كتاباً وأنا أنتظر");
1. تم الطلب 2. أقرأ كتاباً وأنا أنتظر 3. وصل الطعام!
الفصل 13
5 مثالاً · 3 مشروعاً · 5 تمارين
ستتعلم في هذا الفصل أن
async وawaitfetchtry وcatch، وتعرض حالتي التحميل والخطأشغّل هذا البرنامج وانظر جيداً إلى ترتيب المخرجات:
console.log("1. تم الطلب");
setTimeout(() => {
console.log("3. وصل الطعام!");
}, 1000);
console.log("2. أقرأ كتاباً وأنا أنتظر");
1. تم الطلب 2. أقرأ كتاباً وأنا أنتظر 3. وصل الطعام!
وJavaScript الحديثة تسهّل استخدام الوعود بكلمتين. فالدالة الموسومة بـ async تستطيع استخدام await، التي توقف تلك الدالة وحدها حتى يجهز الوعد، دون أن تجمّد أي شيء آخر:
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function makeTea() {
console.log("أغلي الماء…");
await wait(300);
console.log("أنقع الشاي…");
await wait(300);
console.log("انتهيت.");
return "كوب من الشاي";
}
makeTea().then((result) => console.log(result));
console.log("في الأثناء، أجهّز المائدة.");
أغلي الماء… في الأثناء، أجهّز المائدة. أنقع الشاي… انتهيت. كوب من الشاي
fetch(url) ترسل طلب HTTP، مثل الطلبات التي قرأتها في الفصل 4 تماماً، وتُرجع وعداً بالرد. ولكي يعمل المثال في أي مكان حتى بلا إنترنت، يشغّل أولاً خادم واجهة برمجية صغيراً خاصاً به:
node fetch.jsconst http = require("node:http");
// خادم واجهة برمجية صغير له عنوان واحد: /api/products
const products = [
{ id: 1, name: "البرمجة من الصفر", price: 25 },
{ id: 2, name: "كوب بِت", price: 8 },
{ id: 3, name: "ملصق بِت", price: 3 },
];
const server = http.createServer((request, response) => {
if (request.url === "/api/products") {
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify(products));
} else {
response.writeHead(404);
response.end();
}
});
// كود العميل: هذا ما يعمل في التطبيق الحقيقي
async function getJson(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}
server.listen(3001, async () => {
const list = await getJson("http://localhost:3001/api/products");
console.log(list.length, list[0].name);
try {
await getJson("http://localhost:3001/api/missing");
} catch (error) {
console.log("تعذّر التحميل:", error.message);
}
server.close();
});
3 البرمجة من الصفر تعذّر التحميل: HTTP 404
كانت منتجات متجر الفصل 12 مكتوبة داخل shop.js. أما المتاجر الحقيقية فتأخذها من خادم، ليغيّر صاحب المتجر منتجاته دون أن يلمس الكود. فلننقلها إلى ملف JSON بجانب الصفحة:
[
{
"id": 1,
"name": "البرمجة من الصفر",
"price": 25
},
{
"id": 2,
"name": "كوب بِت",
"price": 8
},
{
"id": 3,
"name": "ملصق بِت",
"price": 3
},
{
"id": 4,
"name": "قميص بِت",
"price": 15
},
{
"id": 5,
"name": "قبعة بِت",
"price": 12
}
]
الآن يبدأ catalog فارغاً، ودالة جديدة اسمها start تحمّل البيانات وتعرض الحالات الثلاث. وهذه نهاية shop.js الجديدة، وبقية الملف كما كان في الفصل 12:
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>متجر بِت</title>
<link rel="stylesheet" href="shop.css">
</head>
<body>
<header><h1>متجر بِت</h1></header>
<main>
<section>
<p id="status" role="status"></p>
<div id="products"></div>
</section>
<aside id="cart">
<h2>سلتك</h2>
<ul id="cart-lines"></ul>
<p id="cart-total"></p>
</aside>
</main>
<script src="shop.js"></script>
</body>
</html>
products.json، ومعها القبعة الجديدة.* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; background: #f5f5fb; color: #1e1b2e; }
header { padding: 16px 24px; color: white; background: #4338ca; }
header h1 { margin: 0; }
main { display: grid; grid-template-columns: 1fr 240px; gap: 16px; padding: 16px 24px; }
#products { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 12px; align-content: start; }
.card { background: white; border-radius: 14px; padding: 14px; box-shadow: 0 2px 8px rgba(30, 27, 46, 0.08); }
.card h3 { margin: 0 0 4px; font-size: 1rem; }
.card p { margin: 0 0 10px; color: #db2777; font-weight: 700; }
.card button { width: 100%; padding: 8px; border: 0; border-radius: 999px; color: white; background: #4338ca; font: inherit; cursor: pointer; }
#cart { background: white; border-radius: 14px; padding: 4px 16px 12px; align-self: start; box-shadow: 0 2px 8px rgba(30, 27, 46, 0.08); }
#cart-lines { padding: 0; list-style: none; }
#cart-lines li { display: flex; justify-content: space-between; padding: 4px 0; border-bottom: 1px solid #eef2ff; }
#cart-total { font-weight: 700; font-size: 1.2rem; color: #4338ca; }
@media (max-width: 560px) { main { grid-template-columns: 1fr; } }
#status { font-weight: 700; color: #4338ca; margin: 0 0 8px; }
#status:empty { display: none; }
let catalog = [];
const cart = [];
// ارسم بطاقة لكل منتج
function renderProducts() {
const container = document.querySelector("#products");
for (const product of catalog) {
const card = document.createElement("article");
card.className = "card";
const name = document.createElement("h3");
name.textContent = product.name;
const price = document.createElement("p");
price.textContent = `$${product.price}`;
const button = document.createElement("button");
button.textContent = "أضف إلى السلة";
button.addEventListener("click", () => addToCart(product.id));
card.append(name, price, button);
container.append(card);
}
}
function addToCart(productId) {
const line = cart.find((item) => item.productId === productId);
if (line) {
line.quantity++;
} else {
cart.push({ productId, quantity: 1 });
}
renderCart();
}
// أعد رسم السلة من البيانات كلما تغيرت
function renderCart() {
const list = document.querySelector("#cart-lines");
list.replaceChildren();
let total = 0;
for (const item of cart) {
const product = catalog.find((p) => p.id === item.productId);
const lineTotal = product.price * item.quantity;
total += lineTotal;
const li = document.createElement("li");
li.textContent = `${product.name} × ${item.quantity}`;
const amount = document.createElement("span");
amount.textContent = `$${lineTotal}`;
li.append(amount);
list.append(li);
}
document.querySelector("#cart-total").textContent =
cart.length === 0 ? "سلتك فارغة." : `المجموع: $${total}`;
}
// حمّل المنتجات من الخادم، ثم ارسم الصفحة
async function start() {
const status = document.querySelector("#status");
status.textContent = "جارٍ تحميل المنتجات…";
try {
const response = await fetch("products.json");
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
catalog = await response.json();
status.textContent = "";
renderProducts();
renderCart();
} catch (error) {
status.textContent = "عذراً، تعذّر تحميل المنتجات. حاول مرة أخرى.";
console.error(error);
}
}
start();
مشروع 13.1 · سهل
عُدّ تنازلياً من 3 مع توقف بين الأرقام، ثم قل «انطلق!»، واكتشف ماذا يفعل باقي البرنامج أثناء الانتظار.
ستتدرب على: تغليف setTimeout في وعد (promise)، وawait داخل حلقة، وترتيب تنفيذ الكود غير المتزامن.
wait(ms) من هذا الفصل: تُرجع وعداً يتحقق بعد ms ملي ثانية.async function countdown(from) فيها حلقة for تطبع n ثم await wait(200).countdown(3)، وفي السطر التالي اطبع «استعد…».تلميح: الدالة async تعمل حتى أول await فيها، ثم تعيد التحكم. ولهذا يتسلل «استعد…» بعد الرقم 3.
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function countdown(from) {
for (let n = from; n > 0; n--) {
console.log(n + "…");
await wait(200);
}
console.log("انطلق!");
}
countdown(3);
console.log("استعد…");
3… استعد… 2… 1… انطلق!
مشروع 13.2 · متوسط
حضّر الشاي والخبز والبيض، مرة واحداً بعد الآخر ومرة كلها في الوقت نفسه، وقِس الفرق.
ستتدرب على: دوال تُرجع قيمها عبر الوعود، وPromise.all، وقياس زمن الكود بـ Date.now().
async function make(item, ms) تنتظر ms ثم تُرجع item.seconds(start): الزمن منذ start مقرباً إلى منزلة عشرية واحدة.await الأطباق الثلاثة بالدور (300 و400 و500 ملي ثانية) واطبع الزمن.Promise.all([…])، وانتظرها بـ await، واطبع الزمن من جديد.Promise.all تعيد مصفوفة النتائج بالترتيب نفسه. اطبعها موصولة بـ " + ".تلميح: واحداً بعد الآخر يأخذ مجموع الأزمنة، وكلها معاً يأخذ أطولها فقط. فحين تحتاج الصفحة ثلاث بيانات مستقلة، حمّلها معاً.
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function make(item, ms) {
await wait(ms);
return item;
}
function seconds(start) {
const ms = Date.now() - start;
return (Math.round(ms / 100) / 10).toFixed(1);
}
async function main() {
let start = Date.now();
await make("شاي", 300);
await make("خبز محمص", 400);
await make("بيض", 500);
console.log("واحداً بعد الآخر:", seconds(start), "ثانية");
start = Date.now();
const breakfast = await Promise.all([
make("شاي", 300),
make("خبز محمص", 400),
make("بيض", 500),
]);
console.log("كلها معاً:", seconds(start), "ثانية");
console.log(breakfast.join(" + "));
}
main();
واحداً بعد الآخر: 1.2 ثانية كلها معاً: 0.5 ثانية شاي + خبز محمص + بيض
مشروع 13.3 · تحدٍّ
اسأل واجهة طقس صغيرة عن ثلاث مدن، إحداها غير موجودة، وأكمل التقرير رغم ذلك.
ستتدرب على: fetch، وفحص response.ok، ورمي أخطائك بنفسك، وtry/catch داخل حلقة.
/api/weather/cairo يُرجع JSON، والمدينة المجهولة تُرجع 404.getJson(url): ترمي Error حين تكون response.ok خاطئة.async function report(names): اطبع رسالة تحميل، ثم مرّ على الأسماء وانتظر كل مدينة بـ await.try/catch داخل الحلقة، فتطبع المدينة الخاطئة «لا بيانات» وتكمل الحلقة.try خارج الحلقة وانظر ماذا تخسر.تلميح: مكان try يقرر كم يكسر الخطأ الواحد. فحول الحلقة كلها توقف مدينة خاطئة كل شيء، وحول كل طلب لا تكلّف إلا سطراً واحداً.
node weather.jsconst http = require("node:http");
// واجهة طقس صغيرة: /api/weather/cairo وهكذا
const weather = {
cairo: { city: "القاهرة", temp: 31, sky: "مشمس" },
dubai: { city: "دبي", temp: 35, sky: "حار جداً" },
london: { city: "لندن", temp: 14, sky: "مطر خفيف" },
};
const server = http.createServer((request, response) => {
const name = request.url.replace("/api/weather/", "");
if (weather[name]) {
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify(weather[name]));
} else {
response.writeHead(404);
response.end();
}
});
// كود العميل
async function getJson(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}
async function report(names) {
console.log("جارٍ تحميل الطقس…");
for (const name of names) {
try {
const day = await getJson(`http://localhost:3002/api/weather/${name}`);
console.log(`${day.city}: ${day.temp}°C، ${day.sky}`);
} catch (error) {
console.log(`${name}: لا بيانات (${error.message})`);
}
}
console.log("اكتمل التقرير.");
}
server.listen(3002, async () => {
await report(["cairo", "atlantis", "london"]);
server.close();
});
جارٍ تحميل الطقس… القاهرة: 31°C، مشمس atlantis: لا بيانات (HTTP 404) لندن: 14°C، مطر خفيف اكتمل التقرير.
التمرين 13.1 · سهل
async وawait والدالة wait.for (const n of [3, 2, 1]) { console.log(n); await wait(1000); } console.log("انطلق!"); داخل دالة async.function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function countdown() {
for (const n of [3, 2, 1]) {
console.log(n);
await wait(1000); // الحلقة تتوقف هنا ثانية، دون أن يتجمد البرنامج
}
console.log("انطلق!");
}
countdown();
3 2 1 انطلق!
التمرين 13.2 · سهل
fetch.js أضف عنواناً ثانياً، /api/hello، يُرجع {"message": "أهلاً!"}، واجلبه.else if (request.url === "/api/hello") ترسل JSON.stringify({ message: "أهلاً!" }).node fetch.jsconst http = require("node:http");
// الملف fetch.js من الفصل، مع عنوان ثانٍ: /api/hello
const products = [
{ id: 1, name: "البرمجة من الصفر", price: 25 },
{ id: 2, name: "كوب بِت", price: 8 },
{ id: 3, name: "ملصق بِت", price: 3 },
];
const server = http.createServer((request, response) => {
if (request.url === "/api/products") {
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify(products));
} else if (request.url === "/api/hello") {
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify({ message: "Hi!" }));
} else {
response.writeHead(404);
response.end();
}
});
async function getJson(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}
server.listen(3021, async () => {
const list = await getJson("http://localhost:3021/api/products");
console.log(list.length, list[0].name);
const hello = await getJson("http://localhost:3021/api/hello");
console.log(hello);
console.log(hello.message);
server.close();
});
3 البرمجة من الصفر
{ message: 'Hi!' }
Hi!التمرين 13.3 · متوسط
start() مرة أخرى.catch، ومعالج نقرته يستدعي start().<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>متجر بِت</title>
<link rel="stylesheet" href="../../examples/shop.css">
<style>
#reload { margin-top: 8px; padding: 6px 16px; border: 0; border-radius: 999px; color: white; background: #4338ca; font: inherit; cursor: pointer; }
</style>
</head>
<body>
<header><h1>متجر بِت</h1></header>
<main>
<section>
<p id="status" role="status"></p>
<button id="reload" type="button" hidden>أعد التحميل</button>
<div id="products"></div>
</section>
<aside id="cart">
<h2>سلتك</h2>
<ul id="cart-lines"></ul>
<p id="cart-total"></p>
</aside>
</main>
<script src="shop.js"></script>
</body>
</html>
let catalog = [];
// افتح الصفحة بالعنوان shop.html?fail لتفشل أول محاولة تحميل عمداً، وتجرّب زر إعادة التحميل.
let failOnce = location.search.includes("fail");
const reload = document.querySelector("#reload");
reload.addEventListener("click", () => start());
const cart = [];
// ارسم بطاقة لكل منتج
function renderProducts() {
const container = document.querySelector("#products");
container.replaceChildren();
for (const product of catalog) {
const card = document.createElement("article");
card.className = "card";
const name = document.createElement("h3");
name.textContent = product.name;
const price = document.createElement("p");
price.textContent = `$${product.price}`;
const button = document.createElement("button");
button.textContent = "أضف إلى السلة";
button.addEventListener("click", () => addToCart(product.id));
card.append(name, price, button);
container.append(card);
}
}
function addToCart(productId) {
const line = cart.find((item) => item.productId === productId);
if (line) {
line.quantity++;
} else {
cart.push({ productId, quantity: 1 });
}
renderCart();
}
// أعد رسم السلة من البيانات كلما تغيرت
function renderCart() {
const list = document.querySelector("#cart-lines");
list.replaceChildren();
let total = 0;
for (const item of cart) {
const product = catalog.find((p) => p.id === item.productId);
const lineTotal = product.price * item.quantity;
total += lineTotal;
const li = document.createElement("li");
li.textContent = `${product.name} × ${item.quantity}`;
const amount = document.createElement("span");
amount.textContent = `$${lineTotal}`;
li.append(amount);
list.append(li);
}
document.querySelector("#cart-total").textContent =
cart.length === 0 ? "سلتك فارغة." : `المجموع: $${total}`;
}
// حمّل المنتجات من الخادم، ثم ارسم الصفحة
async function start() {
const status = document.querySelector("#status");
status.textContent = "جارٍ تحميل المنتجات…";
reload.hidden = true;
try {
const response = await fetch(failOnce ? "missing.json" : "../../examples/products.json");
failOnce = false;
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
catalog = await response.json();
status.textContent = "";
renderProducts();
renderCart();
} catch (error) {
status.textContent = "عذراً، تعذّر تحميل المنتجات. حاول مرة أخرى.";
console.error(error);
// أظهر الزر مع رسالة الخطأ؛ والضغط عليه يشغّل start() من جديد ببساطة.
reload.hidden = false;
}
}
start();
التمرين 13.4 · متوسط
Promise.all، واستخدمها لجلب ملفي JSON في الوقت نفسه وطباعة النتيجتين.const [a, b] = await Promise.all([getJson(url1), getJson(url2)]);<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Promise.all</title>
<style>body { font-family: system-ui, sans-serif; margin: 24px; } pre { background: #f5f5fb; padding: 12px; border-radius: 8px; }</style>
</head>
<body>
<h1>Promise.all</h1>
<p>ملفا JSON، يُحمَّلان في الوقت نفسه:</p>
<pre id="out">…</pre>
<script>
async function getJson(url) {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
async function main() {
const [products, settings] = await Promise.all([
getJson("../../examples/products.json"),
getJson("settings.json"),
]);
document.querySelector("#out").textContent =
JSON.stringify(products, null, 2) + "\n\n" + JSON.stringify(settings, null, 2);
}
main().catch((error) => {
document.querySelector("#out").textContent = `تعذّر التحميل: ${error.message}`;
});
</script>
</body>
</html>
node promise-all.jsconst http = require("node:http");
// ملفا JSON، يقدمهما خادم صغير ليحمّلهما fetch.
const files = {
"/products.json": [{ id: 1, name: "كوب بِت", price: 8 }],
"/weather.json": { city: "الإسكندرية", temperature: 24 },
};
const server = http.createServer((request, response) => {
// كل جواب يستغرق 500 ملّي ثانية، لنرى أن الطلبين ينتظران في الوقت نفسه.
setTimeout(() => {
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify(files[request.url]));
}, 500);
});
async function getJson(url) {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
server.listen(3022, async () => {
const started = Date.now();
const [products, weather] = await Promise.all([
getJson("http://localhost:3022/products.json"),
getJson("http://localhost:3022/weather.json"),
]);
console.log(products);
console.log(weather);
// نحو 0.5 ثانية لا ثانية كاملة: الطلبان جريا جنباً إلى جنب.
console.log(`وصل الاثنان في نحو ${Math.round((Date.now() - started) / 100) / 10} ث`);
server.close();
});
[ { id: 1, name: 'كوب بِت', price: 8 } ]
{ city: 'الإسكندرية', temperature: 24 }
وصل الاثنان في نحو 0.5 ث{ "theme": "dark", "language": "ar", "currency": "USD" }
التمرين 13.5 · تحدٍّ
https://api.github.com/users/ متبوعة باسم مستخدم، لتبني صفحة تعرض اسم مستخدم GitHub وصورته وعدد مستودعاته العامة. وتعامل مع حالة «المستخدم غير موجود».`https://api.github.com/users/${name}`، وافحص response.status === 404 لحالة «غير موجود»، واعرض name وavatar_url وpublic_repos.<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>مستخدم GitHub</title>
<style>
body { font-family: system-ui, sans-serif; margin: 24px; max-width: 520px; }
form { display: flex; gap: 8px; }
input, button { font: inherit; padding: 8px 12px; border-radius: 8px; border: 1px solid #c7c5d9; }
button { color: white; background: #1e1b2e; border: 0; cursor: pointer; }
.card { display: flex; gap: 16px; align-items: center; margin-top: 20px; padding: 16px; border-radius: 14px; background: #f5f5fb; }
.card img { border-radius: 50%; }
.error { color: #b91c1c; font-weight: 700; }
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
</style>
</head>
<body>
<h1>ابحث عن مستخدم في GitHub</h1>
<form id="form">
<label for="name" class="visually-hidden">اسم المستخدم</label>
<input id="name" value="octocat" required>
<button>اعرض</button>
</form>
<div id="result" role="status"></div>
<script>
const result = document.querySelector("#result");
async function showUser(name) {
result.textContent = "جارٍ التحميل…";
try {
const response = await fetch(`https://api.github.com/users/${encodeURIComponent(name)}`);
// 404 ليس استثناءً عند fetch: الطلب نجح، لكن المستخدم غير موجود.
if (response.status === 404) {
result.innerHTML = "";
const p = document.createElement("p");
p.className = "error";
p.textContent = `لا يوجد مستخدم باسم "${name}".`;
result.append(p);
return;
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const user = await response.json();
const card = document.createElement("div");
card.className = "card";
const img = document.createElement("img");
img.src = user.avatar_url;
img.alt = "";
img.width = 80;
img.height = 80;
const text = document.createElement("div");
const title = document.createElement("h2");
title.textContent = user.name || user.login;
const repos = document.createElement("p");
repos.textContent = `المستودعات العامة: ${user.public_repos}`;
text.append(title, repos);
card.append(img, text);
result.replaceChildren(card);
} catch (error) {
// لا شبكة، أو طلبات كثيرة (يسمح GitHub بـ 60 طلباً في الساعة دون تسجيل دخول).
result.innerHTML = `<p class="error">تعذّر تحميل المستخدم. حاول لاحقاً.</p>`;
console.error(error);
}
}
document.querySelector("#form").addEventListener("submit", (event) => {
event.preventDefault();
showUser(document.querySelector("#name").value.trim());
});
showUser("octocat");
</script>
</body>
</html>