一、什么是 Async / Await
Async / Await 是现代编程语言中常见的异步编程语法,用于简化异步任务的编写和组织。
它并不是一种独立的异步执行机制,而是一种建立在 Promise、Future 或其他异步计算抽象之上的语言特性。
在 JavaScript 中:
async用于声明异步函数。await用于等待一个 Promise 或 thenable 的结果。async函数始终返回 Promise。await不会阻塞整个 JavaScript 线程,而是暂停当前 async 函数的后续执行。
例如:
async function getUser() {
return {
id: 1,
name: "Alice"
};
}
async function main() {
const user = await getUser();
console.log(user);
}
main();
虽然 getUser() 返回的是普通对象,但由于函数声明了 async,JavaScript 会将返回值包装为一个成功完成的 Promise。
可以将它理解为:
function getUser() {
return Promise.resolve({
id: 1,
name: "Alice"
});
}
两者在基本结果语义上等价,但并不意味着所有细节都可以简单地进行文本替换。
1. Async 的作用
async 用于声明异步函数。
async function calculate() {
return 100;
}
调用:
const result = calculate();
console.log(result);
得到的是 Promise,而不是直接得到数字 100。
通过 then 获取结果:
calculate().then(value => {
console.log(value);
});
输出:
100
Async 函数有两个重要特征:
- 函数返回值会被转换为 Promise 的成功结果。
- 函数内部抛出的异常会使返回的 Promise 以拒绝状态完成。
例如:
async function getValue() {
throw new Error("执行失败");
}
getValue().catch(error => {
console.error(error.message);
});
2. Await 的作用
await 用于等待异步结果。
async function main() {
const result = await Promise.resolve(100);
console.log(result);
}
main();
当执行到 await 时:
- 如果等待的 Promise 已经完成,函数会在后续异步执行阶段继续运行。
- 如果 Promise 尚未完成,当前 async 函数会暂停后续执行。
- JavaScript 执行环境可以继续处理其他任务。
- Promise 完成后,async 函数从暂停位置继续执行。
需要注意:await 不仅可以等待 Promise,也可以接收普通值。普通值会按照已成功完成的结果处理。
3. Async / Await 的核心价值
| 设计目标 | 说明 |
|---|---|
| 简化异步代码 | 减少 Promise 链式嵌套 |
| 改善可读性 | 让任务依赖关系更接近同步代码 |
| 统一异常处理 | 使用 try...catch 处理异步失败 |
| 简化控制流 | 支持条件判断、循环和提前返回 |
| 便于组合任务 | 与 Promise 组合 API 配合使用 |
二、为什么需要 Async / Await
在 Async / Await 出现之前,JavaScript 已经有回调函数和 Promise 两种常见异步编程方式。
Async / Await 主要解决的是异步代码组织和控制流表达问题。
1. 回调函数方式
假设需要依次完成三个任务:
- 查询用户。
- 查询用户订单。
- 查询订单详情。
使用回调函数:
getUser(userId, (user) => {
getOrders(user.id, (orders) => {
getOrderDetail(orders[0].id, (detail) => {
console.log(detail);
});
});
});
这种方式容易产生回调地狱。
主要问题:
- 嵌套层级过深。
- 错误处理分散。
- 任务依赖关系不直观。
- 代码维护困难。
2. Promise 链式调用
使用 Promise 可以改善嵌套结构:
getUser(userId)
.then(user => getOrders(user.id))
.then(orders => getOrderDetail(orders[0].id))
.then(detail => {
console.log(detail);
})
.catch(error => {
console.error(error);
});
Promise 通过 then 建立异步任务之间的依赖关系。
但当业务逻辑涉及复杂条件、循环、异常恢复和多层任务组合时,链式结构仍然可能变得难以阅读。
3. Async / Await 方式
使用 Async / Await:
async function main() {
try {
const user = await getUser(userId);
const orders = await getOrders(user.id);
const detail = await getOrderDetail(orders[0].id);
console.log(detail);
} catch (error) {
console.error(error);
}
}
代码结构更加接近同步编程。
| 对比维度 | 回调函数 | Promise | Async / Await |
|---|---|---|---|
| 代码组织 | 嵌套调用 | 链式调用 | 顺序式写法 |
| 错误处理 | 回调约定 | catch | try...catch |
| 条件分支 | 容易嵌套 | 可以实现 | 接近同步代码 |
| 循环处理 | 需要额外组织 | 需要组合 | 可以直接使用循环 |
| 多任务组合 | 手动控制 | Promise API | await 配合 Promise API |
| 底层机制 | 函数调用 | Promise | 基于 Promise 的语法抽象 |
Async / Await 并没有取代 Promise,而是让 Promise 的使用更加自然。
三、Async 的工作原理
理解 Async / Await,首先需要理解 async 函数的返回值和执行语义。
1. Async 函数始终返回 Promise
普通函数:
function getNumber() {
return 100;
}
调用:
const result = getNumber();
console.log(result);
得到:
100
Async 函数:
async function getNumber() {
return 100;
}
调用:
const result = getNumber();
console.log(result);
得到的是一个 Promise。
可以通过以下方式获取结果:
getNumber().then(value => {
console.log(value);
});
2. 返回值的包装机制
Async 函数返回值会按照 Promise 的解决过程处理。
普通值:
async function getValue() {
return 100;
}
相当于返回一个成功完成的 Promise。
返回 Promise:
async function getValue() {
return Promise.resolve(100);
}
Async 函数会采用返回 Promise 的最终状态和结果,而不是将其作为普通对象直接嵌套。
例如:
async function getValue() {
return Promise.resolve(100);
}
getValue().then(value => {
console.log(value);
});
输出:
100
3. Async 函数的异常处理
Async 函数内部抛出的异常会转换为返回 Promise 的拒绝状态。
async function calculate() {
throw new Error("计算失败");
}
calculate().catch(error => {
console.error(error.message);
});
也可以使用 try...catch 在函数内部处理:
async function calculate() {
try {
throw new Error("计算失败");
} catch (error) {
console.error(error.message);
}
}
这里异常已经被捕获,函数正常结束,因此返回的 Promise 会成功完成,其结果为 undefined。
4. Async 函数执行流程
flowchart TD
A["调用 Async 函数"] --> B["创建返回的 Promise"]
B --> C["执行函数体同步部分"]
C --> D{"是否遇到 await"}
D -->|"否"| E["继续执行函数体"]
D -->|"是"| F["等待异步结果"]
F --> G["暂停当前函数后续执行"]
G --> H["等待结果完成"]
H --> I{"执行结果"}
I -->|"成功"| J["恢复函数执行"]
I -->|"失败"| K["抛出拒绝原因"]
J --> D
K --> L["异常处理或 Promise 拒绝"]
E --> M["函数正常返回"]
M --> N["Promise 成功完成"]
L --> O["Promise 失败完成"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style K fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style L fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style M fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style N fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style O fill:#FBE9E9,stroke:#D9AAAA,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
四、Await 的执行机制
await 是 Async / Await 中最关键的语法。
它的核心作用是暂停当前 async 函数的后续执行,并在等待对象完成后恢复执行。
1. Await 等待 Promise
async function main() {
console.log("开始");
const result = await new Promise(resolve => {
setTimeout(() => {
resolve(100);
}, 1000);
});
console.log("结果:", result);
console.log("结束");
}
main();
输出:
开始
结果:100
结束
执行过程中,await 不会阻塞整个 JavaScript 主线程。
它只会暂停当前 async 函数在 await 之后的部分。
在等待期间,JavaScript 运行时可以继续处理其他任务。
2. Await 等待普通值
await 不要求操作数必须是 Promise。
async function main() {
const a = await 100;
const b = await "hello";
console.log(a);
console.log(b);
}
main();
普通值会按照已成功完成的结果处理。
不过,即使等待普通值,await 之后的代码仍然会以异步恢复的方式继续执行。
例如:
console.log("A");
async function main() {
console.log("B");
await 100;
console.log("C");
}
main();
console.log("D");
输出:
A
B
D
C
原因是:
main()调用时,await之前的代码同步执行。- 执行到
await后,当前 async 函数暂停。 - 主线程继续执行后续同步代码。
- 当前调用栈清空后,async 函数恢复执行。
3. Await 等待 thenable
除了 Promise,await 还可以等待具有 then 方法的对象,即 thenable。
const thenable = {
then(resolve) {
resolve(100);
}
};
async function main() {
const result = await thenable;
console.log(result);
}
main();
JavaScript 会按照 Promise 的解决过程处理 thenable。
这使得 await 能够兼容 Promise 之外的异步结果对象。
4. Await 的恢复机制
flowchart TD
A["执行 Async 函数"] --> B["运行 await 之前的代码"]
B --> C["遇到 await 表达式"]
C --> D["处理等待对象"]
D --> E["暂停当前 Async 函数"]
E --> F["等待 Promise 或 thenable 确定结果"]
F --> G{"等待结果"}
G -->|"成功"| H["恢复执行并得到结果"]
G -->|"失败"| I["恢复执行并抛出异常"]
H --> J["继续执行后续代码"]
I --> K["进入异常处理"]
J --> L["函数继续执行或返回"]
K --> L
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style K fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style L fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
五、Async / Await 与事件循环
在 JavaScript 中,Async / Await 与 Promise 的微任务调度机制紧密相关。
理解事件循环,才能准确判断异步代码的执行顺序。
1. Await 后的代码属于异步恢复过程
例如:
console.log("1");
async function main() {
console.log("2");
await Promise.resolve();
console.log("3");
}
main();
console.log("4");
输出:
1
2
4
3
分析:
- 输出 1。
- 调用
main(),输出 2。 - 执行到
await,暂停当前函数。 - 继续执行同步代码,输出 4。
- 当前调用栈清空。
- 恢复
main(),输出 3。
2. Await 与 Promise.then 的关系
下面两种写法在基本执行顺序上具有相似性:
async function main() {
const result = await Promise.resolve(100);
console.log(result);
}
function main() {
return Promise.resolve(100).then(result => {
console.log(result);
});
}
它们都利用 Promise 的异步结果处理机制。
但 Async / Await 还涉及函数暂停和恢复、词法环境保留以及异常转换等语言层面的语义,不能简单认为它只是 then 的文本替换。
3. 微任务执行顺序
console.log("A");
async function main() {
console.log("B");
await Promise.resolve();
console.log("C");
}
main();
Promise.resolve().then(() => {
console.log("D");
});
console.log("E");
输出:
A
B
E
C
D
原因:
main()执行到await时,会安排恢复执行的微任务。- 随后注册的
then回调进入微任务队列。 - 同步代码先输出 E。
- 先注册的恢复任务先执行,输出 C。
- 后注册的 Promise 回调再输出 D。
4. Await 与事件循环关系
flowchart TD
A["开始执行当前任务"] --> B["执行同步代码"]
B --> C["调用 Async 函数"]
C --> D["执行 await 之前的代码"]
D --> E["遇到 await"]
E --> F["安排恢复执行"]
F --> G["继续执行其他同步代码"]
G --> H["当前任务结束"]
H --> I["执行微任务队列"]
I --> J["恢复 Async 函数"]
J --> K["执行 await 之后的代码"]
K --> L["进入后续事件循环阶段"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style J fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style K fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style L fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
需要注意:
这里描述的是 JavaScript 常见的事件循环执行模型。浏览器和 Node.js 在任务来源、阶段调度及具体运行时行为上存在差异,不应将简化模型当成所有环境的完整调度规范。
六、Async / Await 的异常处理
异步任务的异常处理是 Async / Await 的重要优势之一。
传统 Promise 链通过 catch 处理失败,而 Async / Await 可以使用熟悉的 try...catch。
1. 使用 try...catch
async function getData() {
throw new Error("数据获取失败");
}
async function main() {
try {
const result = await getData();
console.log(result);
} catch (error) {
console.error(error.message);
}
}
main();
当 getData() 返回的 Promise 被拒绝时,await 会将拒绝原因重新表现为当前 async 函数中的异常。
因此可以使用同步代码中熟悉的异常处理结构。
2. 使用 finally 清理资源
async function loadData() {
try {
const result = await fetch("/api/data");
return await result.json();
} catch (error) {
console.error("请求失败", error);
throw error;
} finally {
console.log("请求处理结束");
}
}
finally 适合执行无论成功还是失败都需要进行的清理工作,例如:
- 关闭加载状态。
- 释放临时资源。
- 清理临时状态。
- 记录执行耗时。
注意:finally 中的 return 可能覆盖 try 或 catch 中原本准备返回的值;在异常处理逻辑中通常应避免这样做。
3. 错误传播
如果 Async 函数没有捕获内部异常,其返回的 Promise 会以拒绝状态完成。
async function getUser() {
throw new Error("用户不存在");
}
async function main() {
const user = await getUser();
console.log(user);
}
main().catch(error => {
console.error(error.message);
});
这里异常从 getUser 传播到 main,最终由调用方的 catch 处理。
4. 异常处理流程
flowchart TD
A["调用 Async 函数"] --> B["执行 await"]
B --> C{"异步任务结果"}
C -->|"成功"| D["返回结果"]
C -->|"失败"| E["抛出异常"]
D --> F["继续执行"]
E --> G{"是否存在 try...catch"}
G -->|"是"| H["执行 catch"]
G -->|"否"| I["Async 函数返回拒绝 Promise"]
H --> J{"是否恢复执行"}
J -->|"是"| K["继续执行后续逻辑"]
J -->|"否"| L["向外层传播异常"]
I --> M["调用方处理拒绝"]
L --> M
F --> N["函数完成"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style I fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
style K fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style L fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style M fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style N fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
5. 常见异常处理误区
误区一:没有 await 的异步调用也会被 try...catch 捕获。
async function main() {
try {
getData();
} catch (error) {
console.error(error);
}
}
如果 getData() 返回一个拒绝的 Promise,但没有 await 或其他拒绝处理机制,这里的 try...catch 无法捕获该异步拒绝。
应该写成:
async function main() {
try {
await getData();
} catch (error) {
console.error(error);
}
}
误区二:catch 处理后异常一定继续向外传播。
不一定。
如果 catch 没有重新抛出异常,当前 async 函数通常会继续执行,并可能成功返回。
误区三:所有异步异常都可以被最外层 try...catch 捕获。
不正确。
异常能否被捕获,取决于它是否发生在对应的同步调用栈或是否通过 Promise 拒绝链传递。
七、Async / Await 的顺序执行与并发执行
Async / Await 的代码通常看起来像同步代码,但不能因为使用了 await 就认为任务自动并发。
这是实际开发中最容易出现的性能问题之一。
1. 顺序执行
async function main() {
const user = await getUser();
const orders = await getOrders();
const config = await getConfig();
return { user, orders, config };
}
这里三个任务依次执行。
如果每个任务都需要 1 秒,整体耗时可能接近 3 秒。
适用场景:
- 后续任务依赖前序结果。
- 操作必须按业务顺序执行。
- 存在状态更新或事务依赖。
2. 并发执行
如果任务彼此独立,可以提前创建 Promise,再统一等待。
async function main() {
const userPromise = getUser();
const ordersPromise = getOrders();
const configPromise = getConfig();
const [user, orders, config] = await Promise.all([
userPromise,
ordersPromise,
configPromise
]);
return { user, orders, config };
}
这里三个异步任务可以同时开始,整体等待时间通常接近最慢任务的完成时间,而不是三个任务耗时之和。
注意:这属于并发组织,不代表一定使用多线程或实现 CPU 并行。
3. 顺序与并发对比
| 对比维度 | 顺序执行 | 并发执行 |
|---|---|---|
| 任务启动 | 依次启动 | 尽早启动 |
| 结果依赖 | 适合有依赖任务 | 适合独立任务 |
| 总耗时 | 通常为任务耗时之和 | 通常接近最慢任务耗时 |
| 资源压力 | 相对较低 | 可能更高 |
| 错误处理 | 可逐步处理 | 需要考虑整体失败策略 |
4. 顺序与并发流程
flowchart TD
A["开始执行任务"] --> B{"任务是否存在依赖"}
B -->|"存在依赖"| C["顺序执行"]
B -->|"相互独立"| D["并发启动"]
C --> E["等待当前任务完成"]
E --> F["获取任务结果"]
F --> G{"是否还有后续任务"}
G -->|"有"| C
G -->|"没有"| H["汇总业务结果"]
D --> I["等待所有任务"]
I --> J{"是否全部成功"}
J -->|"是"| H
J -->|"否"| K["执行失败处理"]
K --> L["降级或恢复"]
L --> H
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
style K fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style L fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
八、Async / Await 与 Promise 的组合
Async / Await 建立在 Promise 之上,Promise 的组合 API 仍然是异步任务组织的重要工具。
1. Promise.all
等待所有任务成功:
async function loadDashboard() {
const [user, orders, products] = await Promise.all([
getUser(),
getOrders(),
getProducts()
]);
return {
user,
orders,
products
};
}
如果任何一个 Promise 拒绝,Promise.all 返回的 Promise 就会拒绝。
其他任务不会因此自动取消。
2. Promise.allSettled
当允许部分任务失败时,可以使用 Promise.allSettled:
async function loadResources() {
const results = await Promise.allSettled([
getUser(),
getOrders(),
getProducts()
]);
return results.map(result => {
if (result.status === "fulfilled") {
return result.value;
}
return null;
});
}
适合批量数据获取和允许部分成功的业务。
3. Promise.race
等待最先确定状态的任务:
async function getFastestResult() {
return await Promise.race([
requestServerA(),
requestServerB()
]);
}
无论最先完成的是成功还是失败,都会决定整体结果。