Menu
CoddyTech

Async و Await

جزء من قسم أساسيات Node.js في رحلة Node.js على Coddy. الدرس 16 من 24.

تُقرأ سلسلة من استدعاءات .then بطريقة تختلف عن تصورك للخطوات: اقرأ، ثم حلّل، ثم احفظ.

داخل دالة async، يوقف await التنفيذ مؤقتًا إلى أن يستقر الوعد، ويمنحك قيمته. يؤدي الوعد الفاشل إلى إطلاق استثناء عندها، لذا تتولى try وcatch معالجته. وفي الوحدة، يعمل await أيضًا على المستوى الأعلى.

import { readFile } from 'node:fs/promises';

const loadConfig = async () => {
    try {
        return JSON.parse(await readFile('config.json', 'utf8'));
    } catch {
        return {};
    }
};

const config = await loadConfig();
console.log(config.port ?? 3000);

تعيد دالة async وعدًا دائمًا، لذا ينتظرها المستدعي أيضًا باستخدام await. إذا نسيت await فستحصل على الوعد نفسه، Promise { <pending> }، بدلًا من قيمته.

challenge icon

التحدي

سهل
  • يقرأ store.js الآن البيانات ويكتبها باستخدام node:fs/promises. أضف عبارات await الناقصة كي يعمل كل أمر كما كان من قبل.
  • ينتظر notes.js اكتمال store.add وstore.remove، وهما الآن async.

شغّل node notes.js list أولًا لقراءة رسالة الخطأ، ثم نفّذ add وdone 1 بعد أن يعمل.

جرّب بنفسك

import { existsSync } from 'node:fs';
import { readFile, writeFile } from 'node:fs/promises';

const file = 'notes.json';

// تُعيد readFile وwriteFile الآن وعودًا. انتظر اكتمال كلٍّ منهما باستخدام await.
const load = async () => {
    if (!existsSync(file)) {
        return [];
    }
    try {
        return JSON.parse(readFile(file, 'utf8'));
    } catch (err) {
        console.error(`notes.json is damaged: ${err.message}`);
        process.exit(1);
    }
};

const store = {
    notes: load(),
    async save() {
        writeFile(file, JSON.stringify(this.notes, null, 2));
    },
    async add(text) {
        this.notes.push(text);
        this.save();
        return this.notes.length;
    },
    async remove(n) {
        const [text] = this.notes.splice(n - 1, 1);
        this.save();
        return text;
    },
};

export default store;
quiz iconاختبر نفسك

يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.

جميع دروس أساسيات Node.js