/* 缓存加载函数 cacheLen:最多缓存多少个接口 id:唯一值 name:方法名 syncFunc:加载函数 */ // 缓存最近的20个接口 const methodCacheArr = [] let cacheLen = 20 try { const arr=JSON.parse(localStorage.getItem('queryNoError')) arr.forEach(function (item) { methodCacheArr.push(item) }) cacheLen=arr.length+20; }catch (e) { } function getCacheIndex (val, key) { let has = -1 for (let i = methodCacheArr.length - 1; i >= 0; i--) { if (val === methodCacheArr[i][key]) { has = i break } } return has } export function getCache (name) { const has = getCacheIndex(name, 'name') if (has > -1) { return methodCacheArr[has].res } else { return null } } export function delCache (name) { const has = getCacheIndex(name, 'name') if (has > -1) { methodCacheArr.splice(has, 1) } } export async function limitCache ({id, name, useCache,queryNoError}, syncFunc) { const has = getCacheIndex(id, 'id') if (useCache && has > -1) { if(typeof useCache !== 'number'){ useCache=300; } if (useCache * 1000 + methodCacheArr[has].time > +new Date()) { return methodCacheArr[has].res } } let res = await syncFunc() //更新缓存 if (res && res.flag === 'S') { if (has > -1) { methodCacheArr.splice(has, 1) } methodCacheArr.push({ id: id, queryNoError:queryNoError, name: name, time: +new Date(), res: res }) if (methodCacheArr.length > cacheLen) { methodCacheArr.splice(0, 1) } if(queryNoError){ const arr=methodCacheArr.filter(function (item) { return item.queryNoError; }) if (arr.length > 20) { arr.splice(0, 1) } localStorage.setItem('queryNoError',JSON.stringify(arr)) } }else if(has > -1&&queryNoError){ //兼容查询失败的情况 return methodCacheArr[has].res; } return res }