1. Promise(承诺)——就像取快递
想象你在网上买了个玩具,商家说:”亲,我们会发货,但不确定哪天到。”这时候你会得到一个快递单号,这个单号就是一个 Promise。
Promise 有三种状态:
- pending(等待):快递在路上,还没到
- fulfilled(成功):快递到了,你可以拆包裹了
- rejected(失败):快递丢了或损坏了
代码示例:Promise 就像取快递
// 1. 创建一个 Promise(就像下单)
const receivePackage = new Promise((resolve, reject) => {
// 模拟快递运送(2秒后到)
setTimeout(() => {
const isDelivered = Math.random() > 0.3; // 70%概率送到
if (isDelivered) {
resolve(" 快递到了!"); // 成功
} else {
reject("❌ 快递丢了!"); // 失败
}
}, 2000);
});
// 2. 处理 Promise 结果
receivePackage
.then((result) => {
console.log(result); // 成功:" 快递到了!"
})
.catch((error) => {
console.log(error); // 失败:"❌ 快递丢了!"
});
- .then() → 快递到了该做什么(成功回调)
- .catch() → 快递丢了该做什么(失败回调)
2. async/await —— 像等外卖,必须等它到了才能吃
有时候,我们需要等一个 Promise 完成才能继续,列如:
- 等外卖到了才能吃
- 等女朋友回复消息才能决定晚上去哪
这时候如果用 .then(),代码会有点乱,所以有了 async/await,它让异步代码看起来像同步代码,更容易理解。
代码示例:用 async/await 等外卖
// 模拟外卖 Promise
function orderFood() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const isDelivered = Math.random() > 0.3;
if (isDelivered) {
resolve(" 外卖到了!");
} else {
reject(" 外卖小哥迷路了!");
}
}, 2000);
});
}
// 用 async/await 等待外卖
async function eatDinner() {
try {
console.log("⌛ 等外卖中...");
const result = await orderFood(); // 等外卖到了才继续
console.log(result);
console.log(" 开吃!");
} catch (error) {
console.log(error);
console.log(" 只好吃泡面了...");
}
}
eatDinner();
- async → 这个函数里有异步操作(列如 await)
- await → 等 Promise 完成,再往下执行
- try/catch → 处理成功和失败
3. 终极比喻:Promise vs. async/await
|
场景 |
Promise(.then()) |
async/await |
|
点外卖 |
你下单后去做别的事,外卖到了再通知你 |
你站在门口等,外卖不到你不进门 |
|
写代码 |
用 .then() 处理异步结果 |
用 await 等结果,代码更清晰 |
Promise(.then())的写法
orderFood()
.then((food) => {
console.log(food);
console.log("开吃!");
})
.catch((error) => {
console.log(error);
console.log("吃泡面...");
});
async/await 的写法
async function eat() {
try {
const food = await orderFood(); // 等外卖
console.log(food);
console.log("开吃!");
} catch (error) {
console.log(error);
console.log("吃泡面...");
}
}
哪个更直观? 显然是 async/await,由于它像写同步代码一样简单!
4. 总结
Promise → 像快递单号,代表未来某个操作的结果(成功/失败)
.then() / .catch() → 处理 Promise 的成功或失败
async/await → 让异步代码看起来像同步代码,更易读
- async 标记函数里有 await
- await 会等 Promise 完成再继续
- try/catch 处理错误
最终结论:
- 如果你想写更清晰的异步代码 → 用 async/await
- 如果你只是简单处理异步 → 用 .then()
这样是不是超级好懂?
© 版权声明
文章版权归作者所有,未经允许请勿转载。如内容涉嫌侵权,请在本页底部进入<联系我们>进行举报投诉!
THE END
















暂无评论内容