Menu
CoddyTech

Async and Await

Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 16 of 24.

A chain of .then calls reads differently from how you think about the steps: read, then parse, then save.

Inside an async function, await pauses until a promise settles and gives you its value. A failed promise throws there, so try and catch handle it. In a module, await also works at the top level.

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

An async function always returns a promise, so its caller awaits it too. Forget an await and you get the promise itself, Promise { <pending> }, instead of its value.

challenge icon

Challenge

Easy
  • store.js now reads and writes with node:fs/promises. Add the missing awaits so every command works as before.
  • notes.js awaits store.add and store.remove, which are async now.

Run node notes.js list first to read the error, then add and done 1 once it works.

Try it yourself

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

const file = 'notes.json';

// readFile and writeFile now return promises. Wait for each with 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 iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Node.js Basics