JavaScript异步处理优化:从回调到Promise
性能问题分析
在实际项目中,我们发现一个电商首页存在严重的异步处理性能问题。通过Lighthouse测试发现,页面首次加载耗时3.2秒,其中JavaScript执行时间占1.8秒,主要集中在回调地狱导致的性能瓶颈。
回调地狱问题复现
// 问题代码示例
function fetchUserData(userId, callback) {
setTimeout(() => {
fetch(`/api/user/${userId}`)
.then(res => res.json())
.then(user => {
fetch(`/api/orders/${user.id}`)
.then(res => res.json())
.then(orders => {
fetch(`/api/preferences/${user.id}`)
.then(res => res.json())
.then(preferences => {
callback(null, { user, orders, preferences });
});
});
});
}, 100);
}
Promise优化方案
将上述回调代码重构为Promise链式调用:
// 优化后代码
function fetchUserData(userId) {
return fetch(`/api/user/${userId}`)
.then(res => res.json())
.then(user => {
return Promise.all([
fetch(`/api/orders/${user.id}`).then(res => res.json()),
fetch(`/api/preferences/${user.id}`).then(res => res.json())
]).then(([orders, preferences]) => ({ user, orders, preferences }));
});
}
// 使用示例
fetchUserData(123)
.then(data => {
console.log('用户数据加载完成:', data);
})
.catch(error => {
console.error('加载失败:', error);
});
性能对比测试
通过Chrome DevTools Performance面板分析:
- 回调版本:JavaScript执行时间平均2.1秒,内存占用峰值85MB
- Promise版本:JavaScript执行时间平均0.8秒,内存占用峰值42MB
- 性能提升率:约62%,内存使用减少50%
实际优化建议
- 使用Promise.all()并行处理多个异步请求
- 避免深层嵌套回调,使用async/await简化代码
- 合理设置超时机制防止长时间阻塞
- 使用Web Workers处理复杂计算任务

讨论