Menu
CoddyTech

Promise.all

本课属于 Coddy Node.js 学习旅程的“Node.js 基础”单元。第 25 课,共 33 课。

独立读取可以提供同一个结果的不同部分。启动这两项操作,等待它们返回结果,然后分别将每个结果用于对应的用途。

const [forecast, location] = await Promise.all([
    readFile('forecast.txt', 'utf8'),
    readFile('location.txt', 'utf8'),
]);
console.log(location + ': ' + forecast);

结果的顺序与输入数组一致,即使第二次读取先完成也是如此。你的笔记工具会读取笔记和显示设置。已准备好的 readJson 辅助函数可以处理文件缺失和损坏的情况。先格式化笔记编号,再反转显示行的顺序,这样更改视图时,编号始终对应同一条笔记。

challenge icon

挑战

简单

这一步会打开课程提供的笔记命令行工具项目,而不是你在 Async and Await 中的项目文件(包括 store.js)。你之前的作品仍保留在它自己的课中。编辑 store.js 前,请先阅读提供的文件。这份副本包含笔记命令、JSON 读取器和配置文件。

现在,笔记工具需要同时使用 notes.json 和 settings.json。提供的 readJson(name, fallback) 辅助函数会保留现有的文件错误处理。

  1. 在 store.js 中,用通过 Promise.all 一起读取这两个文件的结果替换空占位符。笔记文件不存在时使用 [];设置文件不存在时使用 {}。
  2. 在 notes.js 中,list 分支已经会生成带编号的行。当 store.settings.sort 为 newest 时,在打印前反转这些行。其他设置都保持原有顺序。

试试 list:在 Notes for you 后面,预期会看到 2. Call Ada、1. Buy milk。将设置改为 oldest 后再试一次:相同的编号会按升序显示。检查前请恢复为 newest。

亲手试试

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

const file = 'notes.json';

const readJson = async (name, fallback) => {
    if (!existsSync(name)) {
        return fallback;
    }
    try {
        return JSON.parse(await readFile(name, 'utf8'));
    } catch (err) {
        console.error(`${name} is damaged: ${err.message}`);
        process.exit(1);
    }
};

// 用两次调用 readJson 的结果替换这些占位内容。
const notes = [];
const settings = {};

const store = {
    notes,
    settings,
    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 基础中的所有课

自己练习: Express 在线编辑器