在学习前端过程中一直没弄明白这个,后面问了AI后才明白。
| 特性 | Promise | async/await |
|---|---|---|
| 语法 | 链式调用 .then().catch() |
类似同步代码的写法 |
| 错误处理 | 使用 .catch()或第二个参数 |
使用 try-catch块 |
| 可读性 | 回调地狱风险 | 代码更清晰易读 |
| 调试 | 调试相对复杂 | 调试更方便,有同步代码的感觉 |
javascript
// Promise 方式
function getUserData(userId) {
return fetchUser(userId)
.then(user => fetchProfile(user.id))
.then(profile => fetchPosts(profile.userId))
.then(posts => {
console.log('所有数据获取完成');
return posts;
})
.catch(error => console.error('出错:', error));
}
// async/await 方式
async function getUserDataAsync(userId) {
try {
const user = await fetchUser(userId);
const profile = await fetchProfile(user.id);
const posts = await fetchPosts(profile.userId);
console.log('所有数据获取完成');
return posts;
} catch (error) {
console.error('出错:', error);
}
}
重要关系
-
async 函数总是返回一个 Promise
-
await 只能在 async 函数中使用
-
await 后面可以跟任何 thenable 对象(主要是 Promise)
javascript
async function example() {
return 'hello'; // 自动包装成 Promise
}
// 等价于
function example() {
return Promise.resolve('hello');
}
总结
-
Promise 是处理异步操作的底层机制
-
async/await 是基于 Promise 的语法糖,让代码更易读写
-
两者可以混合使用,根据场景选择最合适的写法
-
现代 JavaScript 开发中,推荐使用 async/await 来提高代码可读性