Promise
和 async/await
都是 JavaScript 处理 异步操作 的方式,但它们的使用方式和可读性不同。
1️⃣ Promise
特点:
Promise
代表一个未来会完成的异步操作。- 它有三种状态:
pending
(进行中)fulfilled
(成功)rejected
(失败)
- 通过
.then()
处理成功,.catch()
处理错误,.finally()
处理最终操作。
示例:使用 Promise
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve("数据加载成功");
} else {
reject("数据加载失败");
}
}, 1000);
});
}
fetchData().then((result) => console.log(result)); // 成功时执行
.catch(error => console.error(error)) // 失败时执行
.finally(() => console.log("操作完成"));
2️⃣ async/await
特点:
async/await
是Promise
的语法糖,让异步代码看起来更像同步代码,提高可读性。await
只能在async
函数内使用,等待Promise
解析后再执行后续代码。- 使用
try...catch
处理错误,比.catch()
更直观。
示例:使用 async/await
async function fetchData() {
try {
const result = await new Promise((resolve, reject) => {
setTimeout(() => resolve("数据加载成功"), 1000);
});
console.log(result);
} catch (error) {
console.error("发生错误:", error);
} finally {
console.log("操作完成");
}
}
fetchData();
3️⃣ Promise vs async/await 的对比
对比点 | Promise | async/await |
---|---|---|
代码可读性 | 回调嵌套较多,容易形成回调地狱 | 代码更简洁,结构类似同步代码 |
错误处理 | 通过 .catch() 处理错误 | 通过 try...catch 处理错误 |
链式调用 | 适合多个 .then() 串联 | 适合顺序执行多个 await 操作 |
适用场景 | 需要并行执行多个异步操作时更方便 | 需要顺序执行异步代码时更方便 |
4️⃣ 实际开发中如何选择?
✅ 适合使用 async/await
的情况:
- 代码需要按顺序执行,后面的操作依赖前面的结果。
- 代码可读性很重要,比如
try...catch
结构比.catch()
更清晰。
✅ 适合使用 Promise
的情况:
- 需要并行执行多个异步任务,比如
Promise.all()
:Promise.all([fetchUser(), fetchOrders()]) .then(([user, orders]) => console.log(user, orders)) .catch((err) => console.error(err));
- 需要链式调用多个异步操作时,比如
.then().then().catch()
。
总结:
async/await
让代码更清晰,适合顺序执行的异步任务。Promise
更适合并行任务(比如Promise.all()
),适合多个异步任务无依赖的场景。
👉 最佳实践:
在大部分情况下,推荐使用 async/await
,但遇到多个异步任务需要同时执行时,结合 Promise.all()
使用效果更佳!🚀
4o