許多開發人員可能認為他們了解 AbortController,但它的功能遠遠超出了基礎知識。從取消取得請求到管理事件監聽器和 React hooks。
你真的知道AbortController有多強嗎?讓我們來看看:
使用 AbortController 取消取得請求
將 AbortController 與 fetch 結合使用,當然也是最常見的用法。
以下範例示範如何使用 AbortController 建立可取消的取得要求:
fetchButton.onclick = async () => { const controller = new AbortController(); // Add a cancel button abortButton.onclick = () => controller.abort(); try { const response = await fetch('/json', { signal: controller.signal }); const data = await response.json(); // Perform business logic here } catch (error) { const isUserAbort = error.name === 'AbortError'; // AbortError is thrown when the request is canceled using AbortController } };
上面的範例展示了在引入 AbortController 之前不可能實現的功能:以程式方式取消網路請求的能力。取消後,瀏覽器將停止獲取,從而節省網路頻寬。重要的是,取消不必由用戶發起。
controller.signal 提供了一個 AbortSignal 對象,可以與 fetch 等非同步操作進行通信,並允許取消它們。
要將多個訊號合併為一個訊號,可以使用 AbortSignal.any()。方法如下:
try { const controller = new AbortController(); const timeoutSignal = AbortSignal.timeout(5000); const response = await fetch(url, { // Abort fetch if any of the signals are triggered signal: AbortSignal.any([controller.signal, timeoutSignal]), }); const data = await response.json(); } catch (error) { if (error.name === 'AbortError') { // Notify the user of cancellation } else if (error.name === 'TimeoutError') { // Notify the user of timeout } else { // Handle other errors, like network issues console.error(`Type: ${error.name}, Message: ${error.message}`); } }
AbortController 和 AbortSignal 之間的區別
- AbortController:用於透過controller.abort()明確取消關聯訊號。
- AbortSignal:代表訊號物件;它不能直接取消任何內容,但會傳達其中止狀態。
對於 AbortSignal,您可以:
- 使用signal.aborted檢查是否中止。
- 監聽中止事件:
if (signal.aborted) { } signal.addEventListener('abort', () => {});
當使用 AbortController 取消請求時,伺服器將不會處理該請求或發送回應,從而透過減少並發連線來節省頻寬並提高客戶端效能。
AbortController 的常見用例
取消 WebSocket 連接
WebSocket 等較舊的 API 本身並不支援 AbortSignal。相反,您可以像這樣實現取消:
function abortableSocket(url, signal) { const socket = new WebSocket(url); if (signal.aborted) { socket.close(); // Abort immediately if already canceled } signal.addEventListener('abort', () => socket.close()); return socket; }
注意:如果AbortSignal已經中止,則不會觸發中止事件,因此需要提前檢查並處理這種情況。
刪除事件監聽器
傳統上,刪除事件偵聽器需要傳遞完全相同的函數參考:
window.addEventListener('resize', () => doSomething()); window.removeEventListener('resize', () => doSomething()); // This won’t work
使用 AbortController,這變得更容易:
const controller = new AbortController(); const { signal } = controller; window.addEventListener('resize', () => doSomething(), { signal }); // Remove the event listener by calling abort() controller.abort();
對於較舊的瀏覽器,請考慮加入一個polyfill來支援AbortController。
在 React Hook 中管理非同步任務
在 React 中,如果元件在上一個非同步任務完成之前更新,效果可能會無意中並行運行:
function FooComponent({ something }) { useEffect(async () => { const data = await fetch(url + something); // Handle the data }, [something]); return ...>; }
為了避免此類問題,請使用 AbortController 取消先前的任務:
fetchButton.onclick = async () => { const controller = new AbortController(); // Add a cancel button abortButton.onclick = () => controller.abort(); try { const response = await fetch('/json', { signal: controller.signal }); const data = await response.json(); // Perform business logic here } catch (error) { const isUserAbort = error.name === 'AbortError'; // AbortError is thrown when the request is canceled using AbortController } };
在 Node.js 中使用 AbortController
現代 Node.js 包含與 AbortController 相容的 setTimeout 實作:
try { const controller = new AbortController(); const timeoutSignal = AbortSignal.timeout(5000); const response = await fetch(url, { // Abort fetch if any of the signals are triggered signal: AbortSignal.any([controller.signal, timeoutSignal]), }); const data = await response.json(); } catch (error) { if (error.name === 'AbortError') { // Notify the user of cancellation } else if (error.name === 'TimeoutError') { // Notify the user of timeout } else { // Handle other errors, like network issues console.error(`Type: ${error.name}, Message: ${error.message}`); } }
與瀏覽器 setTimeout 不同,此實作不接受回呼;相反,使用 .then() 或 wait.
用於高階調度的任務控制器
瀏覽器正在轉向使用 Scheduler.postTask() 來確定任務優先級,其中 TaskController 擴展了 AbortController。您可以使用它來取消任務並動態調整其優先順序:
if (signal.aborted) { } signal.addEventListener('abort', () => {});
如果不需要優先權控制,可以直接使用AbortController來取代。
結論
AbortController 是現代 JavaScript 開發中的重要工具,提供了管理和取消非同步任務的標準化方法。
它與瀏覽器和 Node.js 環境的整合凸顯了它的多功能性和重要性。
如果您不了解 AbortController,現在是時候擁抱它的全部功能並使其成為非同步程式設計工具包的基石了。
我們是 你真的了解AbortController嗎?,是將 Node.js 專案部署到雲端的首選。
你真的了解AbortController嗎? 是用於 Web 託管、非同步任務和 Redis 的下一代無伺服器平台:
多語言支援
- 使用 Node.js、Python、Go 或 Rust 進行開發。
免費部署無限個專案
- 只需支付使用費用-無請求,不收費。
無與倫比的成本效率
- 即用即付,無閒置費用。
- 範例:25 美元支援 694 萬個請求,平均回應時間為 60 毫秒。
簡化的開發者體驗
- 直覺的使用者介面,輕鬆設定。
- 完全自動化的 CI/CD 管道和 GitOps 整合。
- 即時指標和日誌記錄以獲取可行的見解。
輕鬆的可擴充性和高效能
- 自動擴展,輕鬆處理高並發。
- 零營運開銷 - 只需專注於建置。
在文件中探索更多內容!
在 X 上追蹤我們:@你真的了解AbortController嗎?HQ
閱讀我們的部落格
以上是你真的了解AbortController嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。

JavaScript框架的強大之處在於簡化開發、提升用戶體驗和應用性能。選擇框架時應考慮:1.項目規模和復雜度,2.團隊經驗,3.生態系統和社區支持。

引言我知道你可能會覺得奇怪,JavaScript、C 和瀏覽器之間到底有什麼關係?它們之間看似毫無關聯,但實際上,它們在現代網絡開發中扮演著非常重要的角色。今天我們就來深入探討一下這三者之間的緊密聯繫。通過這篇文章,你將了解到JavaScript如何在瀏覽器中運行,C 在瀏覽器引擎中的作用,以及它們如何共同推動網頁的渲染和交互。 JavaScript與瀏覽器的關係我們都知道,JavaScript是前端開發的核心語言,它直接在瀏覽器中運行,讓網頁變得生動有趣。你是否曾經想過,為什麼JavaScr

Node.js擅長於高效I/O,這在很大程度上要歸功於流。 流媒體匯總處理數據,避免內存過載 - 大型文件,網絡任務和實時應用程序的理想。將流與打字稿的類型安全結合起來創建POWE

Python和JavaScript在性能和效率方面的差異主要體現在:1)Python作為解釋型語言,運行速度較慢,但開發效率高,適合快速原型開發;2)JavaScript在瀏覽器中受限於單線程,但在Node.js中可利用多線程和異步I/O提升性能,兩者在實際項目中各有優勢。

JavaScript起源於1995年,由布蘭登·艾克創造,實現語言為C語言。 1.C語言為JavaScript提供了高性能和系統級編程能力。 2.JavaScript的內存管理和性能優化依賴於C語言。 3.C語言的跨平台特性幫助JavaScript在不同操作系統上高效運行。

JavaScript在瀏覽器和Node.js環境中運行,依賴JavaScript引擎解析和執行代碼。 1)解析階段生成抽象語法樹(AST);2)編譯階段將AST轉換為字節碼或機器碼;3)執行階段執行編譯後的代碼。

Python和JavaScript的未來趨勢包括:1.Python將鞏固在科學計算和AI領域的地位,2.JavaScript將推動Web技術發展,3.跨平台開發將成為熱門,4.性能優化將是重點。兩者都將繼續在各自領域擴展應用場景,並在性能上有更多突破。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Atom編輯器mac版下載
最受歡迎的的開源編輯器

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

Dreamweaver Mac版
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)