Menu
CoddyTech

Promise.all

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

The store now needs two files, the notes and the settings, and reading one after the other waits twice.

Promise.all([a, b]) lets both promises run at the same time and waits until both finish. It gives back their results in the same order as the array, and it fails as soon as one of them fails.

const [user, prefs] = await Promise.all([
    readFile('user.json', 'utf8'),
    readFile('prefs.json', 'utf8'),
]);

Use it when the reads do not depend on each other. When the second one needs the first one's result, await them one by one.

challenge icon

Challenge

Easy
  • store.js reads notes.json and settings.json at the same time with Promise.all. A missing settings file counts as {}.
  • When settings.json holds "sort": "newest", list prints the newest note first. Each note keeps its number.

Run node notes.js list. Then change newest to oldest in settings.json and run it again.

Try it yourself

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

const file = 'notes.json';

const load = async () => {
    if (!existsSync(file)) {
        return [];
    }
    try {
        return JSON.parse(await readFile(file, 'utf8'));
    } catch (err) {
        console.error(`notes.json is damaged: ${err.message}`);
        process.exit(1);
    }
};

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

export default store;

All lessons in Node.js Basics