Fetch API 进阶
Fetch进阶:AbortController取消请求、ReadableStream流式读取响应体、Response.clone()克隆、Service Worker中拦截fetch事件、fetch vs axios选型(原生API能力vs便捷性) · 难度:入门 · +10XP
Fetch API 进阶 —— 流式读取、AbortController、跨域
fetch不仅能发GET/POST请求,还支持流式读取响应体、取消请求、处理跨域等高级功能。
流式读取响应
const response = await fetch('/large-file');
const reader = response.body.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log('收到一块数据:', value.byteLength, 'bytes');
}
取消请求
const controller = new AbortController();
fetch('/api/data', { signal: controller.signal });
controller.abort(); // 取消请求
动手练习
- 基础练习:用AbortController实现5秒超时的fetch。
- 进阶应用:用ReadableStream流式读取大文件并显示下载进度。
- 项目实战:在搜索功能中实现"输入即搜索,新输入取消旧请求"。