背景与价值

  • 长时间悬挂的请求与流式消费会占用资源并影响交互;统一取消与超时治理可提升稳定性。

基本取消


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, 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(fn: () => Promise) {
    if (this.cur >= this.max) await new Promise(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。
  • 稳定性:长驻页面无资源泄漏与并发阻塞。

测试清单

  • 弱网与断网:请求及时取消并回退;流式读取可中断。
  • 大量并发:网关限制下系统稳定,任务队列有序。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部