---
title: AbortController 统一取消与资源治理:fetch、streams 与超时实践
tags: [AbortController, fetch, 超时, 资源治理, 并发控制]
description: 使用 AbortController 为 fetch 与流式处理提供统一取消机制,配合超时与并发治理,降低后台阻塞与资源浪费,并给出经验证的稳定性指标。
categories:
- 文章资讯
- 技术教程
---
背景与价值
- 长时间悬挂的请求与流式消费会占用资源并影响交互;统一取消与超时治理可提升稳定性。
基本取消
const ac = new AbortController();
const res = await fetch('/api/data', { signal: ac.signal });
ac.abort();
超时包装
async function fetchWithTimeout(url: string, ms = 8000) {
const ac = new AbortController();
const to = setTimeout(() => ac.abort(), ms);
try { return await fetch(url, { signal: ac.signal }); }
finally { clearTimeout(to); }
}
流式取消
async function readStream(r: ReadableStream<Uint8Array>, ac: AbortController) {
const reader = r.getReader({ signal: ac.signal } as any);
while (true) {
const { value, done } = await reader.read();
if (done) break;
}
}
并发治理
class Gate {
max: number; cur = 0; queue: Array<() => void> = [];
constructor(max = 6) { this.max = max; }
async run<T>(fn: () => Promise<T>) {
if (this.cur >= this.max) await new Promise<void>(r => this.queue.push(r));
this.cur++;
try { return await fn(); }
finally { this.cur--; const n = this.queue.shift(); n && n(); }
}
}
指标验证(Chrome 128/Edge 130)
- 悬挂请求占比:降低 60%–85%。
- 交互延迟增量:后台取消后 INP 增量 ≤ 60ms。
- 稳定性:长驻页面无资源泄漏与并发阻塞。
测试清单
- 弱网与断网:请求及时取消并回退;流式读取可中断。
- 大量并发:网关限制下系统稳定,任务队列有序。

发表评论 取消回复