有个需求,页面加载有一个组件被加载上百次,这个组件内部会从接口拿数据,有相同的也有不同的。需要拦截这些请求,让相同参数的请求只发送一次,但所有组件都需要拿到数据。axios的处理重复请求,我只看到可以取消,并未统一返回。
type User = {
username: string;
name: string;
}
class RequestStore {
/**
* 根据用户名获取用户信息
* @param username 用户名
*/
getUserByUserName(username: string) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(username)
}, 1000)
})
}
// 缓存请求状态
promiseRecord: Record<string, any> = {};
// 缓存请求的用户信息
userCache: Record<string, any> = {}
timer: number | null = null;
getUserByUsername(username: User["username"]) {
if (this.timer) {
this.timer = window.setTimeout(() => {
this.promiseRecord = {};
this.userCache = {};
if (this.timer) this.timer = null;
}, 500)
}
return this.repeat(username)
}
repeat(username: string) {
if (!this.promiseRecord[username]) {
// 放一个promise
this.promiseRecord[username] = new Promise((resolve, reject) => {
this.getCache(username).then(res => {
this.promiseRecord[username] = null;
resolve(res);
})
})
}
// 请求过
return this.promiseRecord[username];
}
getCache = (username: string) => {
return new Promise((resolve, reject) => {
const data = this.userCache[username];
const request = () => {
this.getUserByUserName(username).then(res => {
this.userCache[username] = res;
resolve(res);
})
}
if (data) {
resolve(data)
} else {
request()
}
})
}
}
const service = new RequestStore();
[1, 2, 3, 12, 1, 3, 213, 12, 3, 12, 3, 12, 1, 2, 12, 2, 12, 1, 2, 1, 1, 11, 1, 1, , 1, 1, 1, 2].forEach(item => {
service.getUserByUsername(String(item))
})