Menu
CoddyTech

Promise

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

回调中再嵌套回调会很难读懂,而且每个回调都必须记得检查 err。

node:fs/promises 会改为返回一个 promise:它是一个代表稍后才会到达的结果的对象。.then(fn) 会在结果到达时运行,.catch(fn) 会在之前的任何步骤失败时运行,.finally(fn) 无论结果如何都会运行。

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

readFile('poem.txt', 'utf8')
    .then((text) => console.log(text.length + ' characters'))
    .catch(() => console.log('No poem today'))
    .finally(() => console.log('Bye'));

在 .then 中抛出的错误也会传到 .catch,因此一个处理程序就能处理读取和解析过程。失败后没有 .catch 处理的 promise 会导致程序崩溃。

challenge icon

挑战

简单

此步骤会打开课程中准备好的命令行笔记工具项目,而不是你在 Callbacks 中的项目文件(包括 count.js)。你之前的作品仍保留在原来的课中。编辑 count.js 前,请先阅读提供的文件。此副本包含异步笔记计数示例。

  • 使用来自 node:fs/promises 的 readFile 和 .then 重写 count.js。
  • 现在,文件缺失时会通过 .catch 打印 No notes yet。
  • Done 仍会最后出现,由 .finally 打印。

先运行 node count.js,再运行 node count.js nothere.json。

不提供参数时,输出依次为 Reading...、2 notes,然后是 Done,每项各占一行。使用 nothere.json 时,中间一行是 No notes yet。

亲手试试

import fs from 'node:fs';

const file = process.argv[2] ?? 'notes.json';

console.log('Reading...');
fs.readFile(file, 'utf8', (err, text) => {
    if (err) {
        console.log(`Cannot read ${file}`);
    } else {
        console.log(`${JSON.parse(text).length} notes`);
    }
    console.log('Done');
});

Node.js 基础中的所有课

自己练习: Express 在线编辑器