Menu
CoddyTech

Promise.all

Coddy Node.js 여정의 Node.js 기초 섹션에 포함된 레슨. 24개 중 17번째.

이제 저장소에는 notes와 설정이라는 두 파일이 필요하며, 하나씩 차례로 읽으면 두 번 기다려야 합니다.

Promise.all([a, b])을 사용하면 두 프로미스가 동시에 실행되고 둘 다 끝날 때까지 기다립니다. 배열과 같은 순서로 결과를 반환하며, 둘 중 하나라도 실패하면 즉시 실패합니다.

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

읽기 작업들이 서로 의존하지 않을 때 사용하세요. 두 번째 작업에 첫 번째 작업의 결과가 필요한 경우에는 하나씩 await하세요.

challenge icon

챌린지

쉬움
  • store.js는 notes.json과 settings.json을 동시에 읽습니다. 설정 파일이 없으면 {}로 간주합니다.
  • settings.json에 "sort": "newest"가 있으면 list는 가장 최근 메모를 먼저 출력합니다. 각 메모의 번호는 그대로 유지됩니다.

node notes.js list를 실행하세요. 그런 다음 settings.json에서 newest를 oldest로 바꾸고 다시 실행하세요.

직접 해보기

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;

Node.js 기초의 모든 레슨