📌 一、核心概念对比图谱
| 概念 | 可视化模型 | 关键特征 |
|---------------|---------------------------|--------------------------------------------------------------------------|
| Promise | [链式结构图] → then → then | 状态机机制(pending/resolved/rejected),通过 then/catch 链式处理异步结果 |
| async/await | [同步代码流程图] | 用同步写法包裹异步操作,await 实现执行暂停与结果解包 |
| try...catch | [保护罩示意图] | 同步错误捕获机制,需与 await 配合捕获异步异常 |
二、三维关系图示(三角模型)
┌───────────┐
│ Promise │ ← 基础异步机制
└─────┬─────┘
│ 被封装为
┌─────▼─────┐
│ async/await │ ← 语法糖
└─────┬─────┘
│ 错误通过
┌─────▼─────┐
│ try...catch │ ← 同步化捕获
└───────────┘
三、代码对比实验室
场景:多层异步请求处理
fetchData()
.then(res => process(res))
.then(data => save(data))
.catch(err => console.log("Promise 捕获:", err));
async function handleAsync() {
try {
const res = await fetchData();
const data = await process(res);
await save(data);
} catch (err) {
console.log("async 捕获:", err);
}
}
错误处理差异演示
try {
fetch(url).then(res => { });
} catch (err) { }
fetch(url)
.then(res => { ... })
.catch(err => { });
try {
const res = await fetch(url);
} catch (err) { }
四、特性对比雷达图(6维度)
Promise async/await
代码简洁性 ★★★☆☆ ★★★★★
错误处理 ★★★★☆ ★★★★★(需try)
可读性 ★★★☆☆ ★★★★★
并行处理 ★★★★★(all) ★★★☆☆
嵌套控制 ★★☆☆☆ ★★★★★
调试难度 ★★★☆☆ ★★☆☆☆
五、协作关系场景示例
混合使用最佳实践
async function hybridExample() {
try {
const [user, product] = await Promise.all([fetchUser(), fetchProduct()]);
const order = await createOrder(user)
.then(addProduct)
.catch(handleCreateError);
return { user, product, order };
} catch (err) {
sentry.captureException(err);
throw new Error('流程失败');
}
}
六、决策树:如何选择异步方案?
是否需处理多个并行异步?
├─ 是 → 使用 Promise.all()
└─ 否 → 是否存在顺序依赖?
├─ 是 → 优先 async/await
└─ 否 → 简单 Promise 链
七、进阶理解:Event Loop 中的差异
| 阶段 | Promise 回调 | async 函数 |
|---------------|-----------------------|---------------------------|
| 执行位置 | 微任务队列 | 微任务队列(await 后代码) |
| 调用栈 | 不影响主线程 | 暂停执行并释放调用栈 |