``` const queryResumeInfo = async () => { // loading.value = true; let params = { candidateId: ls.get("candidateId") }; await getResumeDetail(params) .then((res) => { if (res.code === 200) { // 获取家庭成员信息 familyMemberInfo.value = res.result.familyMemberDto; // 获取面试预约信息 let resultInfo = res.result.reservationDto; reservationInfo.value = resultInfo; applyType.value = resultInfo.applyType; ls.set( "applyType", resultInfo.applyType, 7 * 24 * 60 * 60 * 1000 ); applyPost.value = [resultInfo.applyPost]; applyPostName.value = resultInfo.applyPostName; ls.set("applyPost", applyPost.value.toString(), 24 * 60 * 60 * 1000); candidateName.value = resultInfo.candidateName; email.value = r ```优化代码
时间: 2025-04-08 13:24:31 浏览: 34
<<
从您提供的代码来看,`queryResumeInfo` 函数是一个异步方法,主要用于获取简历详情并处理返回的数据。以下是对该代码的一些优化建议:
### 1. **提取公共逻辑**
将一些通用的操作(如 `ls.set` 和数据赋值)封装成独立的方法或工具函数,减少冗余。
例如:
- 将多次调用的 `ls.set` 提取为一个辅助函数。
- 对于多个属性赋值操作,可以用批量设置的方式简化。
### 2. **增强可读性和模块化**
目前代码中存在较多直接对全局变量(如 `familyMemberInfo.value`, `reservationInfo.value` 等)的修改,这种耦合度较高的写法可能会导致维护困难。可以通过创建局部变量存储中间结果后再统一更新外部状态。
### 3. **错误处理改进**
当前代码未包含异常捕获机制,在实际应用中如果接口请求失败则可能导致程序崩溃。应添加 try-catch 结构以及合理的 fallback 或提示信息。
下面是经过上述调整后的版本示例:
```javascript
const queryResumeInfo = async () => {
const setLoadingState = (status) => (loading.value = status);
try {
setLoadingState(true);
const params = { candidateId: ls.get("candidateId") };
const response = await getResumeDetail(params);
if (!response || response.code !== 200) throw new Error('Failed to fetch resume detail');
updateStateFromResponse(response.result);
} catch(error){
console.error(`Error occurred while fetching resume info: ${error.message}`);
alert('无法加载您的简历,请稍候再试!');
}
finally{
setLoadingState(false);
}
};
function updateLocalStorage(key, value, expiresInMs=86400000){
return ls.set(key,value,expiresInMs);
}
// Centralized function for updating state based on API data.
function updateStateFromResponse(data){
familyMemberInfo.value=data?.familyMemberDto||[];
const resultInfo = data.reservationDto;
reservationInfo.value=resultInfo;
applyType.value=(resultInfo && 'applyType'in resultInfo)?resultInfo.applyType:null;
// Store in localStorage with expiration time of one week and day respectively.
if(applyType.value!==null){
updateLocalStorage("applyType",applyType.value ,7*86400000 );
}
applyPost.value=[...(resultInfo&&'applyPost'in resultInfo?[resultInfo.applyPost]:[])];
if(resultInfo&&typeof resultInfo.applyPostName==='string'){
applyPostName.value=resultInfo.applyPostName;
}
if(updateLocalStorage("applyPost",applyPost.value.join(','),8640000)){
console.log('Applied post updated successfully.');
}
candidateName.value='candidateName'in resultInfo?resultInfo.candidateName:'';
}
```
**主要改动点:**
1. 引入了try...catch结构用于捕捉和处理可能发生的错误;
2. 把所有的localStorage 设置动作集中到一个单独的功能里去了,并设定了默认过期时间参数,默认一天到期;
3. 创建了一个新的内部帮助器updateStateFromResponse()来组织来自服务器响应的所有必要更新步骤;
这样不仅减少了重复代码量还提高了整体健壮性及易懂程度。
阅读全文
相关推荐


















