Menu
CoddyTech

Async und Await

Teil des Abschnitts Node.js-Grundlagen der Node.js-Journey von Coddy. Lektion 16 von 24.

Eine Kette von .then-Aufrufen liest sich anders, als du über die Schritte nachdenkst: lesen, dann parsen, dann speichern.

Innerhalb einer async-Funktion pausiert await, bis ein Promise abgeschlossen ist, und liefert dir seinen Wert. Ein fehlgeschlagenes Promise löst dort einen Fehler aus, den try und catch behandeln. In einem Modul funktioniert await auch auf der obersten Ebene.

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);

Eine async-Funktion gibt immer ein Promise zurück, deshalb wartet auch ihr Aufrufer mit await darauf. Vergisst du ein await, erhältst du das Promise selbst, Promise { <pending> }, statt seines Werts.

challenge icon

Aufgabe

Einfach
  • store.js liest und schreibt jetzt mit node:fs/promises. Füge die fehlenden awaits hinzu, damit jeder Befehl wie zuvor funktioniert.
  • notes.js wartet jetzt auf store.add und store.remove, die nun async sind.

Führe zuerst node notes.js list aus, um den Fehler zu lesen, und danach add und done 1, sobald es funktioniert.

Probier es selbst

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

const file = 'notes.json';

// readFile und writeFile geben jetzt Promises zurück. Warte mit await auf jedes davon.
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 iconTeste dich selbst

Diese Lektion enthält ein kurzes Quiz. Starte die Lektion, um es zu beantworten und deinen Fortschritt zu speichern.

Alle Lektionen in Node.js-Grundlagen