Node.js 异步编程
核对 Node.js 同步阻塞与异步非阻塞 I/O 模型差异、回调函数/Promise/async-await 三种异步范式及错误处理与性能实践。
学完这一章,你能够
- 核对 Node.js 同步阻塞与异步非阻塞 I/O 模型差异、回调函数/Promise/async-await 三种异步范式及错误处理与性能实践。
同步阻塞与异步非阻塞 I/O 模型
同步(Synchronous)代码按书写顺序逐行等待前一步执行结束,而异步(Asynchronous)模型允许程序在等待磁盘读写或网络 I/O 返回期间继续推进后续任务。Node.js 以异步非阻塞 I/O 为核心,因此在高并发网络服务中具备显著优势。
Node.js 的 JavaScript 主线程同一时刻只能执行一个调用栈任务,若以同步方式执行大文件读取或慢查询会阻塞整条服务链路。采用异步 I/O 可在不增加大量阻塞线程的前提下提升应用吞吐量、提高系统资源利用率并改善请求响应体验。
三种主流异步编程方式对比
第一种方式是回调函数(Callbacks):将函数作为参数传入异步接口,待 I/O 完成后再由运行时回调。本站 Node.js v24.22.3 离线实测显示,`fs.readFileSync` 先返回文件内容再执行后续语句(`['sync:hello-async-node', 'after_sync']`),而 `fs.readFile` 立即推进主流程后再回调结果(`['after_async_dispatch', 'cb:hello-async-node']`)。回调写法直接,但多层串行易陷入“回调地狱”且错误分散。
第二种方式是 ES6 引入的 Promise,用对象封装异步操作的最终成功或失败结果,支持 `.then()` 链式编排与集中错误处理。其状态一旦从 `pending` 转为 `fulfilled` 或 `rejected` 即不可逆:实测连续调用 `resolve('settled_once')`、`reject(...)`、`resolve(...)` 后仍固定为 `'settled_once'`,两步 `fs.promises.readFile` 链式拼接输出 `'hello-async-node|step2-payload'`。
第三种方式是 ES2017(ES8)的 `async/await` 语法糖:基于 Promise 让异步流程呈同步阅读结构,配合标准 `try/catch` 统一捕获异常;`await` 在普通函数上下文中需置于 `async` 函数体内(ES 模块另支持顶层 `await`)。实测 `async` 函数顺序读取并拼接两份临时文件返回 `{ ok: true, combined: 'HELLO-ASYNC-NODE+step2-payload' }`。
错误处理规范与性能优化要点
三种范式均需显式处理错误:回调采用错误优先约定,判断 `err` 后必须 `return` 中止后续逻辑(实测缺失文件返回 `code: 'ENOENT'` 且 `hasData: false`);Promise 链末尾应统一挂接 `.catch()` 捕获链路任一环节异常(实测捕获 `'ENOENT'`);`async/await` 则通过 `try/catch` 集中拦截并结构化返回 `{ ok: false, code: 'ENOENT' }`。
工程性能方面需遵循四项原则:避免长时间同步计算阻塞事件循环;简单轻量的内存运算无需强行异步化;对批量异步任务限制并发度以防耗尽文件句柄或连接池(实测并发上限 `2` 调度 5 项任务时峰值并发 `maxActive=2`,有序返回 `[10, 20, 30, 40, 50]`);处理大文件时改用流(Stream)分块读写而非一次性载入内存(实测 `highWaterMark: 32` 读取 100 字节文件分 4 块完成)。
对比同步与异步 I/O 顺序、Promise 链、async/await 错误捕获及并发限流流式读取
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
function deepEqual(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}
const tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'mbsky-node-async-'));
try {
const sampleFile = path.join(tmpDir, 'example.txt');
const secondFile = path.join(tmpDir, 'step2.txt');
const missingFile = path.join(tmpDir, 'does-not-exist.txt');
const streamFile = path.join(tmpDir, 'stream-data.txt');
await fsp.writeFile(sampleFile, 'hello-async-node', 'utf8');
await fsp.writeFile(secondFile, 'step2-payload', 'utf8');
await fsp.writeFile(streamFile, 'A'.repeat(100), 'utf8');
// Case 1: Sync vs Async execution order
const syncOrder = [];
const syncText = fs.readFileSync(sampleFile, 'utf8');
syncOrder.push(`sync:${syncText}`);
syncOrder.push('after_sync');
const asyncOrder = [];
await new Promise((resolve, reject) => {
fs.readFile(sampleFile, 'utf8', (err, data) => {
if (err) {
reject(err);
return;
}
asyncOrder.push(`cb:${data}`);
resolve();
});
asyncOrder.push('after_async_dispatch');
});
const cbErrCode = await new Promise((resolve) => {
fs.readFile(missingFile, 'utf8', (err, data) => {
if (err) {
resolve({ handled: true, code: err.code, hasData: data !== undefined });
return;
}
resolve({ handled: false, code: null, hasData: true });
});
});
const actual1 = { syncOrder, asyncOrder, cbErrCode };
const expected1 = {
syncOrder: ['sync:hello-async-node', 'after_sync'],
asyncOrder: ['after_async_dispatch', 'cb:hello-async-node'],
cbErrCode: { handled: true, code: 'ENOENT', hasData: false },
};
// Case 2: Promise chain, error propagation, and state immutability
const immutableResult = await new Promise((resolve, reject) => {
resolve('settled_once');
reject(new Error('ignored_rejection'));
resolve('ignored_second');
});
const chainResult = await fsp
.readFile(sampleFile, 'utf8')
.then((first) => fsp.readFile(secondFile, 'utf8').then((second) => `${first}|${second}`));
const promiseErrCode = await fsp
.readFile(missingFile, 'utf8')
.then(() => 'unexpected')
.catch((err) => err.code);
const actual2 = { immutableResult, chainResult, promiseErrCode };
const expected2 = {
immutableResult: 'settled_once',
chainResult: 'hello-async-node|step2-payload',
promiseErrCode: 'ENOENT',
};
// Case 3: async/await + try/catch error handling
async function processFiles(targetPath) {
try {
const data = await fsp.readFile(targetPath, 'utf8');
const extra = await fsp.readFile(secondFile, 'utf8');
return { ok: true, combined: `${data.toUpperCase()}+${extra}` };
} catch (err) {
return { ok: false, code: err.code };
}
}
const asyncOk = await processFiles(sampleFile);
const asyncFail = await processFiles(missingFile);
const actual3 = { asyncOk, asyncFail };
const expected3 = {
asyncOk: { ok: true, combined: 'HELLO-ASYNC-NODE+step2-payload' },
asyncFail: { ok: false, code: 'ENOENT' },
};
// Case 4: Bounded concurrency & streaming large file
async function runWithConcurrency(items, limit, worker) {
let active = 0;
let maxActive = 0;
const results = new Array(items.length);
let nextIndex = 0;
async function runner() {
while (nextIndex < items.length) {
const idx = nextIndex++;
active += 1;
if (active > maxActive) maxActive = active;
results[idx] = await worker(items[idx]);
active -= 1;
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => runner()));
return { maxActive, results };
}
const bounded = await runWithConcurrency([1, 2, 3, 4, 5], 2, async (n) => {
await new Promise((r) => setTimeout(r, 10));
return n * 10;
});
const streamStats = await new Promise((resolve, reject) => {
let chunks = 0;
let bytes = 0;
const rs = fs.createReadStream(streamFile, { highWaterMark: 32 });
rs.on('data', (chunk) => {
chunks += 1;
bytes += chunk.length;
});
rs.on('end', () => resolve({ chunks, bytes }));
rs.on('error', reject);
});
const actual4 = {
maxActive: bounded.maxActive,
results: bounded.results,
streamChunks: streamStats.chunks,
streamBytes: streamStats.bytes,
};
const expected4 = {
maxActive: 2,
results: [10, 20, 30, 40, 50],
streamChunks: 4,
streamBytes: 100,
};
const cases = [
{ name: 'sync_vs_async_order', passed: deepEqual(actual1, expected1), expected: expected1, actual: actual1 },
{ name: 'promise_chain_and_error', passed: deepEqual(actual2, expected2), expected: expected2, actual: actual2 },
{ name: 'async_await_try_catch', passed: deepEqual(actual3, expected3), expected: expected3, actual: actual3 },
{ name: 'concurrency_limit_and_stream', passed: deepEqual(actual4, expected4), expected: expected4, actual: actual4 },
];
console.log(JSON.stringify({ version: process.version, cases }));
} finally {
await fsp.rm(tmpDir, { recursive: true, force: true });
}
- 核对同步与异步执行顺序、ENOENT 错误捕获、Promise 状态不可逆、最大并发 2 限流与 100 字节 4 块流式读取。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
当前源码 SHA256:c1c0431608e08a6c71fb0eda5d046459968a20c8696e1c0ee506de88c46fdb3d
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
ZIP SHA256:47502afaf4714662dc69e07feef670057cbc9fd2863fee5dd619b25713343910
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Node.js 中为什么不能依赖同步 API 读取大文件?回调函数、Promise 与 async/await 各自的错误处理边界是什么?
展开参考解答
同步 I/O 会阻塞单线程事件循环导致并发请求停滞,大文件更应使用 Stream 分块处理;回调需检查首参 err 并及时 return,Promise 通过链尾 .catch() 捕获上游异常,async/await 使用 try/catch 捕获 await 拒绝的错误。