思路:
import { singleton } from "./singleton";
class Cache {
statusMap = new Map();
cacheMap = new Map();
cbMap = new Map();
constructor() {
}
setCache(request) {
const cacheKey = this.guidGeneratorRequestKey(request);
if (this.statusMap.has(cacheKey)) {
const status = this.statusMap.get(cacheKey);
if (status === 'complete') {
return Promise.resolve(this.cacheMap.get(cacheKey));
}
if (status === 'pending') {
return new Promise((resolve, reject) => {
if (this.cbMap.has(cacheKey)) {
const arr = this.cbMap.get(cacheKey);
arr.push({
onSuccess: resolve,
onFail: reject,
})
this.cbMap.set(cacheKey, arr)
} else {
this.cbMap.set(cacheKey, [
{
onSuccess: resolve,
onFail: reject,
}
])
}
})
}
}
this.statusMap.set(cacheKey, 'pending');
return new Promise((resolve, reject) => {
xx({
url: request.url,
method: request.method || 'get',
header: {
},
data: request.params,
timeout: 10000,
success: (res) => {
console.log('[cache]: params, url, res--setCache:', request.params, request.url, res);
const token = res.data.data || '';
if (res.status == 200 || res.statusCode == 200) { // iOS: status;Android:statusCode
this.statusMap.set(cacheKey, 'complete');
this.cacheMap.set(cacheKey, token);
resolve(token);
} else {
this.statusMap.delete(cacheKey)
reject(res);
}
if (this.cbMap.has(cacheKey)) {
const arr = this.cbMap.get(cacheKey);
for (let list of arr) {
list.onSuccess && list.onSuccess(token);
}
this.cbMap.delete(cacheKey)
}
},
failure: (error) => {
console.error('[cache]: error--setCache:', error);
reject(error);
},
});
})
}
guidGeneratorRequestKey(config) {
return `url=${ config.url }&method=${ config.method }¶ms=${ JSON.stringify(config.params) }`;
}
}
export default singleton(Cache);
以上为基本demo,,此方法有两处待优化:
网站声明:如果转载,请联系本站管理员。否则一切后果自行承担。
添加我为好友,拉您入交流群!
请使用微信扫一扫!