Node.js 非阻塞 I/O 模式導致連續異步操作需層層嵌套回調:
// 經典的「金字塔厄運」
step1((value1) => {
step2(value1, (value2) => {
step3(value2, (value3) => {
step4(value3, (value4) => {
// 處理 value4
});
});
});
});
缺點:錯誤處理分散、程式碼難閱讀、維護成本高、變數作用域混亂。
Pending (進行中) → Fulfilled (成功) / Rejected (失敗),狀態不可逆。onFulfilled 返回非 Promise 值 → 下一個 then 的 onFulfilled 接收該值;返回 Promise → 狀態跟隨該 Promise。catch / onRejected 捕獲。q 庫封裝 Node.js 回調風格 APIq 是早期流行的 Promise 實現,現代 Node.js (v8+) 內建 util.promisify,原理相同。
const fs = require("fs");
const q = require("q"); // npm install q
// 封裝單一異步函數
function readFilePromise(filename) {
const deferred = q.defer();
fs.readFile(filename, "utf8", (err, data) => {
if (err) deferred.reject(err);
else deferred.resolve(data);
});
return deferred.promise;
}
// 使用 .then 鏈式調用
readFilePromise("a.txt")
.then(content => {
console.log("a.txt 內容:", content);
return readFilePromise("b.txt"); // 返回 Promise,鏈式繼續
})
.then(content => {
console.log("b.txt 內容:", content);
return readFilePromise("c.txt");
})
.then(content => console.log("c.txt 內容:", content))
.catch(err => console.error("讀取失敗:", err))
.finally(() => console.log("所有操作結束"));
util.promisify / fs.promisesNode.js v10+ 內建 Promise 版 API,無需額外依賴:
const fs = require("fs").promises; // 或 require("fs/promises") Node 14+
async function readFiles() {
try {
const a = await fs.readFile("a.txt", "utf8");
console.log("a:", a);
const b = await fs.readFile("b.txt", "utf8");
console.log("b:", b);
const c = await fs.readFile("c.txt", "utf8");
console.log("c:", c);
} catch (err) {
console.error("失敗:", err);
} finally {
console.log("結束");
}
}
readFiles();
Promise.all / Promise.allSettled// 並發讀取多個檔案
const files = ["a.txt", "b.txt", "c.txt"];
// 所有成功才繼續,任一失敗即拋錯
Promise.all(files.map(f => fs.readFile(f, "utf8")))
.then(([a, b, c]) => console.log("全部成功:", a, b, c))
.catch(err => console.error("至少一個失敗:", err));
// 全部完成才繼續,不因單個失敗中斷 (ES2020)
Promise.allSettled(files.map(f => fs.readFile(f, "utf8")))
.then(results => {
results.forEach((r, i) => {
if (r.status === "fulfilled") console.log(files[i], "成功:", r.value);
else console.error(files[i], "失敗:", r.reason);
});
});
q.nfbind / util.promisifyAll 批量轉換// q 庫批量轉換物件所有回調方法
const q = require("q");
const fs = require("fs");
const fsPromised = q.denodeify(fs); // 或 q.nfbind(fs)
// fsPromised.readFile("x.txt").then(...)
// Node.js 內建批量轉換
const { promisifyAll } = require("util");
const fs = require("fs");
promisifyAll(fs); // 新增 readFileAsync, writeFileAsync 等方法
fs.readFileAsync("x.txt").then(...);
// 封裝統一錯誤格式
class AppError extends Error {
constructor(code, message, status = 500) {
super(message);
this.code = code; this.status = status;
}
}
// 中間件統一捕獲
app.use((err, req, res, next) => {
if (err instanceof AppError) return res.status(err.status).json({ code: err.code, message: err.message });
console.error(err);
res.status(500).json({ code: "INTERNAL", message: "伺服器錯誤" });
});
// ❌ 錯誤:忘記 return Promise,導致鏈式中斷
getUser().then(user => {
getPosts(user.id); // 缺少 return
}).then(posts => { /* posts 為 undefined */ });
// ✅ 正確
getUser().then(user => getPosts(user.id)).then(posts => { /* ... */ });
// 循序 (有依賴)
const user = await getUser();
const posts = await getPosts(user.id);
const comments = await getComments(posts[0].id);
// 並發 (無依賴)
const [users, posts, comments] = await Promise.all([
getUsers(), getPosts(), getComments()
]);
fs.promises、async/await,無需引入 q 等第三方庫。Promise.all/allSettled/race/any 等組合子,靈活控制並發與錯誤策略。async/await 是語法糖,本質仍是 Promise,**理解 Promise 機制是寫好非同步代碼的前提**。