1. 网络层面的优化
- 设置合理的超时时间:通过
AbortController
来设置请求超时,避免长时间等待无响应的请求。
import { useCallback } from 'qwik';
const fetchWithTimeout = useCallback(async (url, options = {}, timeout = 5000) => {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, { ...options, signal: controller.signal });
clearTimeout(id);
return response;
} catch (error) {
if (error.name === 'AbortError') {
throw new Error('Request timed out');
}
throw error;
}
}, []);
- 队列化请求:对于高并发请求,可以使用队列的方式来限制同时发出的请求数量,防止网络过载。
class RequestQueue {
constructor(private maxConcurrent = 3) {
this.pending = [];
this.active = 0;
}
private pending: (() => Promise<void>)[];
private active: number;
enqueue(request: () => Promise<void>) {
this.pending.push(request);
this.processQueue();
}
async processQueue() {
while (this.pending.length > 0 && this.active < this.maxConcurrent) {
this.active++;
const request = this.pending.shift();
try {
await request?.();
} finally {
this.active--;
this.processQueue();
}
}
}
}
// 使用示例
const queue = new RequestQueue();
queue.enqueue(() => fetchWithTimeout('url1'));
queue.enqueue(() => fetchWithTimeout('url2'));
2. 数据格式校验与转换的改进
- 数据格式校验:使用
zod
等库来进行数据格式校验。
import { z } from 'zod';
// 定义数据格式
const dataSchema = z.object({
key1: z.string(),
key2: z.number()
});
const fetchAndValidate = async (url) => {
const response = await fetchWithTimeout(url);
const data = await response.json();
const result = dataSchema.safeParse(data);
if (!result.success) {
throw new Error('Data format validation failed');
}
return result.data;
};
const transformData = (data) => {
// 进行数据转换操作
return {
newKey1: data.key1.toUpperCase(),
newKey2: data.key2 * 2
};
};
const fetchTransformAndValidate = async (url) => {
const data = await fetchAndValidate(url);
return transformData(data);
};
3. 完善异常处理机制
- 全局异常捕获:在 Qwik 应用中,可以使用
useErrorBoundary
来全局捕获异常。
import { useErrorBoundary } from 'qwik';
export const ErrorBoundary = () => {
const { error, reset } = useErrorBoundary();
if (error) {
// 处理异常,例如记录日志、显示友好提示
console.error('An error occurred:', error);
return <div>An error occurred. Please try again later.</div>;
}
return null;
};
- 请求异常处理:在
fetchWithTimeout
等函数中,已经处理了请求超时等异常,在调用这些函数的地方,可以进一步对异常进行处理。
const MyComponent = () => {
const handleFetch = async () => {
try {
const result = await fetchTransformAndValidate('url');
console.log('Fetched and transformed data:', result);
} catch (error) {
console.error('Error in fetch and transform:', error);
}
};
return <button onClick={handleFetch}>Fetch Data</button>;
};