Promise 是現代 JavaScript 的基礎,但掌握非同步控制流程需要超越基本的「.then()」鏈。本文探討了中高階開發人員生產應用程式所需的高階 Promise 模式,從並發控製到錯誤處理和取消。
超越基礎的承諾景觀
JavaScript 在 Promise 上提供了四種靜態方法來組合非同步操作,每種方法適合不同的場景:
| 方法 | 解決時間 | 拒絕何時 | 使用案例 |
|---|---|---|---|
Promise.all | 所有承諾兌現 | 任何承諾都被拒絕 | 並行 API 調用,全部必需 |
Promise.allSettled | 所有的承諾都兌現了 | 從來沒有 | 結果好壞參半,記錄所有結果 |
Promise.race | 第一個承諾落定 | 第一個承諾被拒絕 | 超時競爭條件 |
Promise.any | 第一個承諾解決了 | 所有承諾均被拒絕 | 首次成功回應模式 |
const results = await Promise.allSettled([
fetch("/api/users").then(r => r.json()),
fetch("/api/posts").then(r => r.json()),
fetch("/api/comments").then(r => r.json()),
]);
const successful = results.filter(r => r.status === "fulfilled").map(r => r.value);
當您需要處理部分結果(即使某些操作失敗)時,「Promise.allSettled」特別有用,例如批次資料同步,其中單一記錄失敗不應中止整個批次。
並發控制
同時運行太多 Promise 可能會壓垮 API、資料庫或瀏覽器。並發限制器對任務進行排隊並確保只有指定數量的任務同時執行:
@@@代碼區塊1@@@
此模式支援背壓:當達到並發限制時,循環將暫停,直到至少一個任務完成。對於更複雜的需求,「p-limit」、「p-queue」和「p-throttle」等函式庫提供了附加功能,包括優先權佇列和速率限制。
非同步/等待最佳實踐
循環中的順序「await」是一個常見的效能缺陷。每次迭代都會等待前一個 Promise 解析後再開始下一個 Promise,即使沒有依賴項也是如此:
// Slow: sequential execution
for (const id of ids) {
const data = await fetch(`/api/items/${id}`).then(r => r.json());
process(data);
}
// Fast: parallel execution
const results = await Promise.all(
ids.map(id => fetch(`/api/items/${id}`).then(r => r.json()))
);
results.forEach(process);
僅當每個步驟都依賴先前的結果時才使用順序“await”。對於獨立操作,始終首選“Promise.all”以最大化吞吐量。非同步函數中的錯誤處理受益於具有類型化錯誤類別的結構化 try-catch:
class ApiError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
async function fetchData(url) {
const response = await fetch(url);
if (!response.ok) {
throw new ApiError(response.status, await response.text());
}
return response.json();
}
錯誤處理和彈性
生產應用程式必須優雅地處理 Promise 拒絕。全域拒絕追蹤捕獲未處理的錯誤:
// Browser
window.addEventListener("unhandledrejection", (event) => {
console.error("Unhandled rejection:", event.reason);
event.preventDefault();
});
// Node.js
process.on("unhandledRejection", (reason, promise) => {
console.error("Unhandled rejection at:", promise, "reason:", reason);
});
對於不穩定的外部服務,斷路器模式可以防止重複呼叫失敗的端點:
class CircuitBreaker {
constructor(fn, options = {}) {
this.fn = fn;
this.failureCount = 0;
this.threshold = options.threshold || 5;
this.timeout = options.timeout || 30000;
this.state = "CLOSED";
}
async call(...args) {
if (this.state === "OPEN") {
throw new Error("Circuit breaker is open");
}
try {
const result = await this.fn(...args);
this.failureCount = 0;
return result;
} catch (error) {
this.failureCount++;
if (this.failureCount >= this.threshold) {
this.state = "OPEN";
setTimeout(() => { this.state = "HALF_OPEN"; }, this.timeout);
}
throw error;
}
}
}
使用 AbortController 取消
Promise 本身並不是可取消的,但 AbortController 提供了一種標準機制來中止獲取請求並透過非同步流傳播取消:
function createTimeoutSignal(ms) {
const controller = new AbortController();
setTimeout(() => controller.abort(), ms);
return controller.signal;
}
async function fetchWithTimeout(url, ms = 5000) {
const signal = createTimeoutSignal(ms);
try {
const response = await fetch(url, { signal });
return response.json();
} catch (error) {
if (error.name === "AbortError") {
throw new Error(`Request timed out after ${ms}ms`);
}
throw error;
}
}
此模式支援任何非同步操作逾時、請求重複資料刪除(其中正在進行的請求在呼叫方之間共用)以及元件卸載時清理非同步流。
結論
進階 Promise 模式將非同步 JavaScript 從容易出錯的狀態轉變為健壯且可維護的狀態。為每個場景選擇正確的 Promise 組合器,限制並發以保護下游服務,建立非同步函數以提高可讀性,實現斷路器以實現彈性,並使用 AbortController 來取消串流。這些模式構成了現代 JavaScript 應用程式中生產級非同步程式碼的基礎。

