🎓 作者简介: 前端领域优质创作者
🚪 资源导航: 传送门=>
🎬 个人主页: 江城开朗的豌豆
🌐 个人网站: 江城开朗的豌豆 🌍
📧 个人邮箱: YANG_TAO_WEB@163.com 📩
💬 个人微信: y_t_t_t_ 📱
📌 座 右 铭: 生活就像心电图,一帆风顺就证明你挂了。 💔
👥 QQ群: 906392632 (前端技术交流群) 💬
作为前端开发者,Promise就像我的瑞士军刀,几乎每天都会用到。今天我要分享Promise在实际开发中的高频使用场景,这些都是我亲身实践过的经验总结。
1. 异步请求处理:告别回调地狱
记得我刚学前端时,回调函数嵌套让我头疼不已。Promise的出现彻底改变了这种情况。
// 以前的我
fetchData(function(data1) {
processData(data1, function(data2) {
saveData(data2, function(result) {
console.log('最终结果:', result);
});
});
});
// 现在的我
fetchData()
.then(processData)
.then(saveData)
.then(result => {
console.log('最终结果:', result);
})
.catch(error => {
console.error('处理失败:', error);
});
2. 多个异步操作并行处理
上周我需要同时获取用户基本信息和订单记录,Promise.all帮了大忙。
const getUserInfo = fetch('/api/user');
const getOrders = fetch('/api/orders');
Promise.all([getUserInfo, getOrders])
.then(([userInfo, orders]) => {
console.log('我的信息:', userInfo);
console.log('我的订单:', orders);
})
.catch(error => {
console.log('加载失败:', error);
});
3. 竞速场景:谁快用谁
在开发性能优化时,我经常用Promise.race来实现超时控制。
const fetchWithTimeout = (url, timeout = 3000) => {
return Promise.race([
fetch(url),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('请求超时')), timeout)
]);
};
// 我的使用示例
fetchWithTimeout('/api/data')
.then(data => console.log('获取成功:', data))
.catch(error => console.log('我的错误处理:', error));
4. 顺序执行异步任务
有时候我需要按顺序执行多个异步操作,Promise链式调用是我的首选。
const task1 = () => new Promise(resolve => {
setTimeout(() => {
console.log('我的第一个任务完成');
resolve(1);
}, 1000);
});
const task2 = (input) => new Promise(resolve => {
setTimeout(() => {
console.log(`我的第二个任务收到输入: ${input}`);
resolve(input + 1);
}, 500);
});
task1()
.then(task2)
.then(result => {
console.log('最终结果:', result); // 输出2
});
5. 错误处理更优雅
Promise让错误处理变得直观明了,这是我的最爱。
function getMyProfile() {
return fetch('/api/my-profile')
.then(response => {
if (!response.ok) {
throw new Error('获取我的资料失败');
}
return response.json();
});
}
getMyProfile()
.then(profile => {
console.log('我的资料:', profile);
})
.catch(error => {
console.error('哎呀,出错了:', error);
showErrorToast(error.message);
});
6. 配合async/await更香
自从有了async/await,我的异步代码看起来就像同步代码一样清晰。
async function loadMyData() {
try {
const user = await fetch('/api/me');
const posts = await fetch(`/api/users/${user.id}/posts`);
console.log('我的帖子:', posts);
return posts;
} catch (error) {
console.log('加载我的数据失败:', error);
throw error;
}
}
// 我的调用方式
loadMyData().then(posts => {
renderMyPosts(posts);
});
7. 创建延迟执行
有时候我需要延迟执行某些操作,Promise也能派上用场。
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// 我的使用示例
async function showWelcomeMessage() {
console.log('欢迎来到我的主页');
await delay(2000);
console.log('这里是我的作品展示');
}
showWelcomeMessage();
8. 缓存异步结果
为了避免重复请求,我经常用Promise实现简单缓存。
const myCache = {};
function getMyData(id) {
if (!myCache[id]) {
myCache[id] = fetch(`/api/data/${id}`)
.then(res => res.json())
.catch(error => {
delete myCache[id];
throw error;
});
}
return myCache[id];
}
// 我的调用方式
getMyData(123).then(data => {
console.log('我的缓存数据:', data);
});
我的Promise使用心得
- 简单异步操作:直接使用.then().catch()
- 多个并行请求:Promise.all是首选
- 错误处理:统一在catch中处理
- 代码可读性:async/await让代码更清晰
- 性能优化:合理使用缓存和竞速
Promise的这些使用场景已经成为了我开发工作中的标准模式。刚开始可能会觉得有点抽象,但一旦掌握,你会发现它能让你的代码质量提升一个档次。
大家在实际项目中使用Promise还遇到过哪些有趣的场景?欢迎在评论区分享你的经验!