async/await 让异步代码读起来像同步代码。它本质上仍然是 Promise,只是把 then 链改成了更直观的 await。多个互不依赖的请求可以用 Promise.all 并行发出。
本节要点
- async 函数总是返回 Promise。
- await 会暂停当前函数,直到 Promise 完成。
- try/catch 可以捕获 await 抛出的错误。
- Promise.all 并行执行,全部成功才返回;Promise.allSettled 会保留每个结果。
可运行示例
示例分别用串行和并行方式请求三次,每次服务端延迟 600 毫秒,对比总耗时。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>async/await 与并发</title>
</head>
<body>
<h1>串行与并行</h1>
<button id="serial">串行请求</button>
<button id="parallel">并行请求</button>
<pre id="output"></pre>
<script>
const output = document.getElementById('output');
async function requestOne(id) {
const start = performance.now();
const response = await fetch(`/ajax/demo/echo.php?delay=600&id=${id}`);
await response.json();
return Math.round(performance.now() - start);
}
document.getElementById('serial').addEventListener('click', async () => {
const start = performance.now();
const times = [];
for (let id = 1; id <= 3; id++) {
times.push(await requestOne(id));
}
output.textContent = `串行耗时:${Math.round(performance.now() - start)}ms\n` +
`单次耗时:${times.join(', ')}ms`;
});
document.getElementById('parallel').addEventListener('click', async () => {
const start = performance.now();
const times = await Promise.all([requestOne(1), requestOne(2), requestOne(3)]);
output.textContent = `并行耗时:${Math.round(performance.now() - start)}ms\n` +
`单次耗时:${times.join(', ')}ms`;
});
</script>
</body>
</html>运行说明:先点“串行请求”,再点“并行请求”。串行总耗时约为单次的三倍,并行总耗时接近单次。 在线运行示例 →
什么时候串行,什么时候并行
后一个请求依赖前一个结果时只能串行,例如先登录再拉取用户信息。互不依赖的列表请求适合并行,例如同时加载文章、评论和推荐。并发数过大时还应限制同时进行的请求数量,避免压垮浏览器或服务端。
错误处理
Promise.all 中任意一个请求失败,整体会进入 catch。如果希望部分失败也继续处理,可以使用 Promise.allSettled,它会返回每个请求的状态和值。
提示:await 只能写在 async 函数内部。在普通函数里使用会直接报语法错误。