这是在 Node 中处理异步操作的三代方案 — 每一代都比前一代提高了可读性,但都基于相同的事件循环基础。
1. 回调函数 — 最初的方案("回调地狱")
js
fs.(, {
(err) (err);
fs.(, {
(err) (err);
db.(a + b, {
(err) (err);
});
});
});
这是在 Node 中处理异步操作的三代方案 — 每一代都比前一代提高了可读性,但都基于相同的事件循环基础。
fs.(, {
(err) (err);
fs.(, {
(err) (err);
db.(a + b, {
(err) (err);
});
});
});
Node 的约定是错误优先回调 ((err, result))。它们能工作,但会嵌套很深,错误处理也很分散 — 难以阅读和维护。
readFile("a.txt")
.then(a => readFile("b.txt").then(b => a + b)) // return a promise → chain waits
.then(combined => db.save(combined))
.catch(handle); // ONE place for all errors
Promise 代表一个未来值;.then 链接步骤,.catch 处理链中的任何错误 — 比嵌套回调更扁平。
async function combine() {
try {
const a = await readFile("a.txt"); // pause until resolved
const b = await readFile("b.txt");
await db.save(a + b);
} catch (err) {
handle(err); // normal try/catch works
}
}
async/await 是 Promise 的语法糖 — 它读起来像自顶向下的同步代码,使用普通的 try/catch,是推荐的现代风格。
// ❌ sequential — slow
const a = await getA(); const b = await getB();
// ✅ parallel — both at once
const [a, b] = await Promise.all([getA(), getB()]);
Callbacks → Promises → async/await
All use the event loop. Promises wrap callbacks; async/await wraps Promises.
Modern code: async/await, with Promise.all to parallelize independent ops.
异步处理在 Node 中是不可避免的(所有 I/O 都是异步的)。
理解这个演变过程 — 错误优先回调(在较旧的 API/库中仍然常见)、Promise(可链接的)和 async/await(可读的、默认的)— 使你能够阅读任何代码库并编写清晰的异步逻辑。
知道它们在底层都是同一个事件循环机制,并记住用 Promise.all 并行化独立操作,是正确高效的异步 Node 代码的关键。