class CacheHelper {
store = {}
getCache(key) {
const cache = this.store[key]
if (!cache) {
return null
}
const curTime = new Date().getTime()
if (curTime > cache.expireTime) {
this.removeCache(key)
return null
}
return cache.value
}
removeCache(key) {
delete this.store[key]
}
setCache(key, value, time = 1000 * 60 * 10) {
this.store[key] = {
value,
expireTime: new Date().getTime() + time,
}
}
promiseGlobalCacheWrapper(fn, keyBuilder, time = 1000 * 60 * 10) {
let that = this
return async function (...args) {
const key = typeof keyBuilder === 'string' ? keyBuilder : keyBuilder(...args)
let cacheValue = that.getCache(key)
console.log('是否找到缓存', cacheValue)
if (!cacheValue) {
fn.bind(this, ...args)
cacheValue = await fn(...args)
if (cacheValue) {
that.setCache(key, cacheValue, time)
}
}
return cacheValue
}
}
}
function sleep(time) {
return new Promise(reslove => {
setTimeout(() => {
reslove()
}, time)
})
}
const cacheHelper = new CacheHelper()
async function test(p) {
return new Promise(reslove => {
setTimeout(() => {
console.log('test:', p)
reslove({ p })
}, 1000)
})
}
const testWrapper = cacheHelper.promiseGlobalCacheWrapper(test, 'hello', 1000 * 2)
const testWrapper2 = cacheHelper.promiseGlobalCacheWrapper(test, p => `demo:${p}`, 1000 * 2)
;(async () => {
console.log('testWrapper:', 1)
await testWrapper(10)
console.log('testWrapper:', 2)
await testWrapper(10)
console.log('testWrapper:', 3)
await testWrapper(10)
await sleep(3000)
console.log('testWrapper:', 4)
await testWrapper(10)
console.log('testWrapper2:', 1)
await testWrapper2(10)
console.log('testWrapper2:', 2)
await testWrapper2(10)
console.log('testWrapper2:', 3)
await testWrapper2(10)
await sleep(3000)
console.log('testWrapper2:', 4)
await testWrapper2(10)
console.log('testWrapper2:', 5)
await testWrapper2(9)
})()