主要的区别在于:
异步函数 - 使用 await,执行时不会blocking,但获取数据时组件已渲染
同步函数 - 直接返回数据,组件渲染需等待执行结束
使用异步函数的潜在风险:
如果异步请求时间过长,组件会先渲染,导致页面空白或显示不正确
获取数据失败时,无法准确得到失败信息来源
同步函数的优点:
组件渲染会等待数据就绪,避免空状态问题
获取数据失败会直接抛出异常,可以明确错误来源
所以,如果获取标签配置数据非关键,可以使用异步函数,但需要注意加载状态。
如果是关键数据,建议使用同步函数获取,甚至提前获取,以免影响组件的渲染。
需要根据应用特点来权衡异步带来的好处和风险。
CR自己的代码
async mounted() {
if (localStorage.getItem('tagConfig')) {
this.tagConfig = JSON.parse(localStorage.getItem('tagConfig'));
} else {
const tagConfig = (await getComListEnums()).data;
localStorage.setItem('tagConfig', JSON.stringify(tagConfig));
this.tagConfig = tagConfig;
}
}
一个很简单的逻辑 先去判断本地缓存里有没有数据存储,有就取本地数据
没有就取请求接口并且储存 但是考虑到异步函数是否会有风险 决定改为同步
主要改动:
getFreshConfig
改为同步函数,直接返回结果
不需要 async/await
组件渲染会等待配置就绪
同步函数也更容易处理错误。
这个修改可以避免异步函数的一些风险,确保组件只在数据获取完成后才渲染。
// data中声明tagConfig
mounted() {
try {
const cachedConfig = localStorage.getItem('tagConfig')
const cacheData = JSON.parse(cachedConfig)
if (cacheData) {
this.tagConfig = cacheData
} else {
// 获取最新配置(同步)
const result = getFreshConfig()
const freshConfig = result
// 缓存
localStorage.setItem('tagConfig', JSON.stringify(freshConfig))
this.tagConfig = freshConfig
}
} catch (err) {
// 处理错误
}
},
methods: {
// 同步函数
getFreshConfig() {
const result = getComListEnums()
return result.data
}
}