如何简化API URL调用中的Switch-Case逻辑?求最佳实践
简化方案与最佳实践
1. 移除冗余的switch-case分支
你的rpcCall函数中所有case的逻辑完全一致,完全不需要用switch区分不同URL,直接统一处理即可。另外注意原代码中状态码判断逻辑错误:resolve.status !== 200 || 201 会始终为true(因为201是真值),正确的判断应该是检查状态码是否不在[200,201]范围内。同时,无需手动封装Promise,因为fetch本身就返回Promise。
优化后的rpcCall:
const rpcCall = async (baseURL: string) => { const res = await fetch(baseURL); if (![200, 201].includes(res.status)) { throw new Error(`Request failed with status ${res.status}`); } return res; };
2. 修复并简化递归的checkToken函数
原checkToken存在多个问题:async函数未正确返回Promise、变量名错误(baseUrl应为listUrl)、返回值错误(直接返回listUrl[index]而非请求结果)。用async/await重构后,逻辑更清晰:
let listUrl: Array<string> = ['URL-1', 'URL-2', 'URL-3', 'URL-n']; const checkToken = async (index = 0): Promise<string> => { // 边界处理:所有URL都尝试失败 if (index >= listUrl.length) { throw new Error('All API endpoints failed'); } try { await rpcCall(listUrl[index]); // 如果请求成功,返回当前URL return listUrl[index]; } catch (err) { // 请求失败,递归尝试下一个URL return checkToken(index + 1); } };
3. 额外最佳实践建议
- 避免递归过深:如果URL列表很长,递归可能导致栈溢出,建议用循环替代递归:
const checkTokenWithLoop = async (): Promise<string> => { for (const url of listUrl) { try { await rpcCall(url); return url; } catch {} } throw new Error('All API endpoints failed'); }; - 添加错误信息:在抛出错误时携带具体信息,便于调试。
- 参数化配置:如果后续不同URL需要不同的状态码或处理逻辑,可以用配置数组替代硬编码,比如:
const urlConfigs = [ { url: 'URL-1', allowedStatus: [200, 201] }, { url: 'URL-2', allowedStatus: [200] }, // ...其他配置 ]; const rpcCallWithConfig = async (config: { url: string; allowedStatus: number[] }) => { const res = await fetch(config.url); if (!config.allowedStatus.includes(res.status)) { throw new Error(`Request failed with status ${res.status}`); } return res; };
内容的提问来源于stack exchange,提问作者Fery1320
相关产品推荐
相关产品推荐

