Class CacheHttp{constructor(Max){this.max = Max; this.cacheList = {}; } cache(handler){ return (... args)=>{ return new Promise((resolve,reject)=>{ let key = JSON.stringify(args); Resolve (this.cachelist [key])}else{console.log('cache data ') resolve(this.cachelist [key])}else{console.log('cache data ') resolve(this.cachelist [key])}else{ Console. log(' Request data ') handler(... args).then(res=>{ resolve(res) this.cacheList[key] = res; let keys = Object.keys(this.cacheList); If (keys.length>this.max){delete keys[0]}}). Catch (err=>{reject(err)})}})}} return new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(1) },2000) }) } const cacheHttp = new CacheHttp(100); CacheGet = cachehttp. cache(get) cacheGet('/ API /article? Id =1',{id:1}). Then (res=>{console.log(' get data ',res)}) setTimeout(()=>{cacheGet('/ API /article? Id = 1 '{1} id:). Then (res = > {the console. The log (' access to data, res)})}, 4000).Copy the code
Birth background: the article details page repeatedly triggers (the list page enters again, the previous page, the next page), repeatedly requests the background interface, resulting in resource waste.
Note: The return value of the function to be cached must be PROMISE, and the state is changeable
Suitable scenario: article details, display content