JavaScript 异步编程与网络请求
浏览器里的 JS 是单线程的:一个时刻只做一件事,所以"等待"必须异步化。这篇从事件循环讲到 Promise 再到 Fetch,覆盖请求封装、超时、重试、CORS 这些和接口联调日日相对的东西。主线现代浏览器(ES2022 + 现行 Fetch 标准)。
一、异步编程概述
1.1 为什么需要异步
网络请求、定时器、用户操作都是"不知道什么时候完成"的事。如果同步等待,页面会卡死:
// 假设有个同步的 xhr(不存在,但想象一下)
const data = syncGet('/api/user'); // 这 2 秒里页面点不动、动画全停所以 JS 的等待方式是:登记一个回调,先忙别的,事件来了再执行回调。
1.2 事件循环与任务队列
console.log('1');
setTimeout(() => console.log('4'), 0); // 宏任务
Promise.resolve().then(() => console.log('3')); // 微任务
console.log('2');
// 输出:1 2 3 4执行顺序的规则:
- 同步代码按顺序执行(
1 2) - 微任务(Promise 回调、
queueMicrotask、MutationObserver)在当前任务结束后、渲染前全部清空(3) - 宏任务(setTimeout、事件回调、I/O)每轮循环取一个(
4)
每次循环:取一个宏任务执行 → 清空全部微任务 → (可能渲染)→ 下一个宏任务理解这个模型的实际价值:
setTimeout(fn, 0)的任务排在同步代码和微任务之后——"让 DOM 先更新再读尺寸"常用它- Promise 的
.then总是比同轮的 setTimeout 先执行 - 长任务(大循环)会阻塞渲染和事件响应,拆成小块用
setTimeout/scheduler.yield()让出主线程
// 大循环分片,避免页面卡死
async function chunkedLoop(total, chunk = 1000) {
for (let i = 0; i < total; i++) {
if (i % chunk === 0) await new Promise(r => setTimeout(r, 0));
process(i);
}
}二、从回调到 Promise
2.1 回调地狱
// Node 风格回调嵌套三层就已经难读
getUser(userId, (err, user) => {
if (err) return handle(err);
getOrders(user.id, (err, orders) => {
if (err) return handle(err);
getOrderDetail(orders[0].id, (err, detail) => {
if (err) return handle(err);
render(detail); // 箭头形代码,错误处理重复三遍
});
});
});问题:嵌套深、错误处理重复、难以并发执行。
2.2 Promise 的状态与 API
const p = new Promise((resolve, reject) => {
// 执行器同步执行;resolve/reject 二选一,只第一次有效
setTimeout(() => resolve('成功数据'), 1000);
// reject(new Error('失败'));
});
p.then(value => console.log(value)) // 成功
.catch(err => console.error(err)) // 失败(链上任何一环出错都到这)
.finally(() => console.log('清理')); // 无论成败三个铁律:
- 状态单向流转:pending → fulfilled 或 pending → rejected,定了就不能改
.then返回新 Promise(不是 this),链式调用靠这个- 链上抛错/返回 rejected promise,会被最近的
.catch捕获——不用每层 catch
// 链式:值在 then 之间传递
fetchUser(id)
.then(user => fetchOrders(user.id)) // 返回 Promise,自动展开
.then(orders => render(orders))
.catch(err => showError(err)); // 全链一个 catch2.3 Promise 组合方法
const tasks = [fetchA(), fetchB(), fetchC()];
Promise.all(tasks) // 全部成功才成功;一个失败立即失败(其余继续但不等待)
.then(([a, b, c]) => {}); // 结果数组保序
Promise.allSettled(tasks) // 等全部结束,不失败;每项 {status, value|reason}
.then(results => results.forEach(r => console.log(r.status)));
Promise.race(tasks) // 第一个定结果(成功或失败都算)——超时控制用它
Promise.any(tasks) // 第一个成功;全失败才失败(AggregateError)
// 并发请求经典需求:3 个商品接口一起发,全部回来再渲染
const [detail, comments, related] = await Promise.all([
fetchDetail(id), fetchComments(id), fetchRelated(id),
]);Promise.all 的一个失败让其他请求"白跑"(结果被丢弃但请求已发出),埋点/上报类任务单独处理,别混在 all 里。
2.4 async/await
// 异步写法同步读,错误用 try/catch
async function loadDetail(id) {
try {
const detail = await fetchDetail(id);
const comments = await fetchComments(detail.id);
render(detail, comments);
} catch (err) {
showError(err);
} finally {
hideLoading();
}
}等价 .then 链,但可读性好一个量级。注意:
// 1. await 串行 = 一个等一个。没依赖关系的用 Promise.all 并发
const a = await fetchA(); // 1s
const b = await fetchB(); // 1s 总共 2s
const [a2, b2] = await Promise.all([fetchA(), fetchB()]); // 总共 1s
// 2. for 循环里 await 是串行的——批量处理要控制并发(见 5.3)
for (const item of items) {
await upload(item); // 一个个传
}
// 3. async 函数永远返回 Promise
async function f() { return 1; }
f() instanceof Promise; // true
f().then(v => console.log(v)); // 1
// 4. 顶层 await 只在 ES 模块里能用(script type="module")
// const data = await fetch('/api'); // 普通 script 里 SyntaxError错误处理模式:把 async 函数当普通函数调,失败不 catch 会产生 unhandledrejection。统一在调用链顶端 catch,或用封装好的 request 层统一处理。
三、XMLHttpRequest
Fetch 之前的唯一选择,现在仍值得了解——进度事件(上传 progress)、老浏览器兼容、以及读老代码:
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/user?id=42'); // 初始化(还没发)
xhr.responseType = 'json'; // json/text/blob/arraybuffer/document
xhr.timeout = 5000; // 超时(毫秒)
xhr.addEventListener('load', () => {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.response); // 已按 responseType 解析
} else {
console.error('HTTP 错误', xhr.status);
}
});
xhr.addEventListener('error', () => console.error('网络错误'));
xhr.addEventListener('timeout', () => console.error('超时'));
xhr.addEventListener('progress', e => {
if (e.lengthComputable) console.log(e.loaded / e.total);
});
xhr.send(); // 发送
xhr.abort(); // 取消// POST JSON
const xhr2 = new XMLHttpRequest();
xhr2.open('POST', '/api/user');
xhr2.setRequestHeader('Content-Type', 'application/json');
xhr2.send(JSON.stringify({ name: '甲' }));
// 上传进度——Fetch 目前做不到(UploadStream 未普及),传大文件还用 xhr
xhr2.upload.addEventListener('progress', e => console.log(e.loaded, e.total));load 事件不代表成功:4xx/5xx 也触发 load(只是 status 不同),只有网络层失败才触发 error。判断成功必须查 status。
四、Fetch API
// 基本 GET
const res = await fetch('/api/user');
const data = await res.json(); // res.json()/text()/blob()/arrayBuffer()
// POST JSON
const res2 = await fetch('/api/user', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: '甲' }),
});4.1 Response 与 Request
res.ok; // status 200-299
res.status; // 200
res.statusText; // 'OK'
res.headers.get('Content-Type');
res.headers.forEach((v, k) => {});
// body 是流——只能读一次!
await res.text(); // 第一次 OK
await res.text(); // TypeError: body used already
// 要多次用先 clone
const clone = res.clone();4.2 错误处理:fetch 的特殊性
// fetch 只在网络层失败时 reject(断网、DNS、CORS 拦截)
// HTTP 404/500 照样 resolve!必须自己查 ok
async function request(url, options = {}) {
const res = await fetch(url, options);
if (!res.ok) {
throw new HttpError(res.status, await res.text().catch(() => ''));
}
return res;
}4.3 超时与取消
// AbortController:超时 + 手动取消统一方案
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);
try {
const res = await fetch('/api/slow', { signal: controller.signal });
const data = await res.json();
} catch (err) {
if (err.name === 'AbortError') console.error('超时或被取消');
else console.error(err);
} finally {
clearTimeout(timeout);
}
// 现代写法:AbortSignal.timeout(5000) 内置超时信号(Chrome 103+)
const res = await fetch('/api/slow', { signal: AbortSignal.timeout(5000) });页面切换/组件卸载时 abort 请求:请求回来了往已销毁的组件里 setState,是 React/Vue 时代的经典警告来源。
4.4 凭据与模式
fetch('/api/user', {
credentials: 'include', // 携带 cookie(跨域时必须服务端允许)
mode: 'cors', // cors / no-cors / same-origin
cache: 'no-cache', // 缓存策略
redirect: 'follow', // follow / error / manual
});同源请求默认带同源 cookie,跨域要 credentials: 'include' + 服务端 CORS 允许。mode: 'no-cors' 的响应是 opaque 的,读不了内容(只能用于埋点类"发出去就行"的请求)。
五、同源策略与 CORS
5.1 同源限制
同源 = 协议 + 域名 + 端口 完全相同。https://a.com 和 https://a.com:443、http://a.com、https://b.a.com、https://a.com:8443 都不同源。
同源策略限制的是脚本发起的跨域请求读取响应(请求能发出去,响应被浏览器拦截)。不受限的:<script>、<img>、<link>、<form> 提交等标签式加载(JSONP、图片 CDN 的原理)。
5.2 CORS 通信机制
服务端通过响应头声明允许的来源:
# 简单请求:直接发,响应带头
Access-Control-Allow-Origin: https://your-site.com
# 带凭据
Access-Control-Allow-Origin: https://your-site.com
Access-Control-Allow-Credentials: true预检请求(OPTIONS):非简单请求(如 Content-Type: application/json、自定义头、PUT/DELETE)浏览器先自动发 OPTIONS 探路,服务端返回允许的方法和头,才发真正的请求:
OPTIONS /api/user
Access-Control-Allow-Origin: https://your-site.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400 # 预检结果缓存,减少 OPTIONS5.3 常见 CORS 报错排查
| 现象 | 原因 |
|---|---|
No 'Access-Control-Allow-Origin' header | 服务端没配 CORS / 没放行你的源 |
| 带 cookie 时报错 | Allow-Origin 不能是 *(配了通配又不带 credential),且请求要 credentials: 'include' |
| OPTIONS 404/405 | 服务端没处理 OPTIONS 路由 |
| 自定义头被拦 | Allow-Headers 没放行该头 |
| 开发环境跨域 | 用 dev server 代理(Vite server.proxy),而不是给服务端乱开口子 |
// Vite 开发代理示例(vite.config.js)
export default {
server: {
proxy: {
'/api': {
target: 'http://backend:8080',
changeOrigin: true,
// rewrite: p => p.replace(/^\/api/, ''),
},
},
},
};代理把跨域变同源,开发环境零配置、不碰服务端,是标准做法。
六、请求封装
把重复逻辑收进一层:统一错误、超时、JSON 处理、基础路径:
const BASE = 'https://api.example.com';
class HttpError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
async function request(path, { method = 'GET', params, body, timeout = 10000, ...rest } = {}) {
const url = new URL(BASE + path);
if (params) Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
const res = await fetch(url, {
method,
headers: {
...(body ? { 'Content-Type': 'application/json' } : {}),
...rest.headers,
},
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(timeout),
credentials: 'include',
});
if (!res.ok) {
const msg = await res.text().catch(() => res.statusText);
throw new HttpError(res.status, msg);
}
return res.status === 204 ? null : res.json();
}
// 用
request('/users', { params: { page: 1, size: 20 } })
.then(data => render(data))
.catch(err => {
if (err instanceof HttpError && err.status === 401) redirectLogin();
else showError(err.message);
});6.1 重试
async function withRetry(fn, { retries = 2, delay = 500 } = {}) {
try {
return await fn();
} catch (err) {
if (retries <= 0) throw err;
await new Promise(r => setTimeout(r, delay));
return withRetry(fn, { retries: retries - 1, delay: delay * 2 }); // 指数退避
}
}
withRetry(() => request('/flash-sale'), { retries: 2 });重试的边界:只对幂等请求(GET)或无副作用的操作重试;支付、下单这类 POST 重试可能重复扣款。网络错误的判断:err instanceof TypeError(fetch 网络层失败)才值得重,4xx 不用。
6.2 并发控制
批量任务(如批量上传 100 个文件)全并发会打爆浏览器/服务端,限制同时在跑的数量:
async function runWithLimit(tasks, limit = 4) {
const results = [];
const executing = new Set();
for (const task of tasks) {
const p = Promise.resolve().then(() => task());
results.push(p);
executing.add(p);
p.finally(() => executing.delete(p)); // 完成的移出池子
if (executing.size >= limit) {
await Promise.race(executing); // 池子满了,等最快的那个完成
}
}
return Promise.all(results);
}
const files = Array.from({ length: 100 }, (_, i) => () => upload(fileList[i]));
runWithLimit(files, 4); // 最多 4 个同时传七、实战:搜索建议(debounce + 竞态处理)
输入联想有两个坑:每敲一字都发请求(浪费)、后发先至(旧响应覆盖新响应)。AbortController 一次解决:
const input = document.getElementById('search');
let controller = null;
input.addEventListener('input', async e => {
const q = e.target.value.trim();
if (!q) return hideSuggestions();
controller?.abort(); // 取消上一个未完成的请求
controller = new AbortController();
try {
const list = await request('/search/suggest', {
params: { q },
timeout: 5000,
});
// 旧请求已 abort,不会走到这;走到这的一定是最新的
renderSuggestions(list);
} catch (err) {
if (err.name !== 'AbortError') showError(err.message);
}
});配合 debounce(见BOM 篇计时事件)体验更好:停止输入 300ms 才发请求。
八、Web API 开发速览
前端视角的 REST 约定:
| 方法 | 语义 | 幂等 |
|---|---|---|
| GET | 查询 | 是 |
| POST | 创建/触发 | 否 |
| PUT | 整体更新 | 是 |
| PATCH | 局部更新 | 否 |
| DELETE | 删除 | 是 |
前后端交互的三条老实话:
- 分页/筛选/排序参数统一放 query,POST body 放业务数据——别把查询条件塞 body
- 错误格式约定好:HTTP status 表达大类,body 里带 code + message,前端按 code 分支(401 跳登录、403 提示无权限、5xx Toast + 重试入口)
- 接口版本演进用路径(
/api/v2/...),不要用 header——浏览器直接打开链接调试方便
九、常见坑速查
| 写法 | 结果 | 原因 |
|---|---|---|
fetch 对 404 不 reject | "成功"进 then 了 | 要查 res.ok |
两个 await res.text() | 第二次报错 | body 流只能读一次 |
| for 里 await 发 100 个请求 | 串行,慢 100 倍 | 用 Promise.all + 并发控制 |
Promise.all 一个失败其他全废 | 结果被丢弃 | 需要容错用 allSettled |
| 取消请求后没有 catch AbortError | 控制台一片红 | 判断 err.name === 'AbortError' 后忽略 |
| 后台页面定时请求停了 | 正常 | 定时器节流 + 请求可能被挂起 |
credentials: 'include' 但 CORS 报错 | 服务端不能 Allow-Origin: * | 必须精确 origin + Allow-Credentials |
new Promise 执行器里抛错 | promise 被 reject | 规范行为,但链上没 catch 就成了 unhandledrejection |
忘了 return 的 .then 回调 | 后续拿不到值 | then 里要 return 才能把值传给下一环 |
