Encapsulation of asynchronous interface data and methods for reading cached data

usage

RequestCache (getProductList(), // Promise method getCache('productList'), / / read cache asynchronous method (list, isCache) = > {/ / whether to obtain the result data and method for caching data / / list: interface returned data or data/cache/isCache: whether to cache data enclosing setState ({list: isCache? list&&list.length! = = 0? list:null : list} ()=>{ if(! isCache){ setCache('productList') } } ) } )Copy the code

Function encapsulation

RequestCache (Request :Promise<any>, readCache:Promise<any>, resolve:(result:any,isCache:boolean)=>void ){ let requestFinished = false; const timestamp = new Date(); request.then((res)=>{ requestFinished = true; resolve(result,false) }).catch(e=>{}) readCache.then((res)=>{ if(! requestFinished && res){ resolve(JSON.parse(res),true); } }).catch(e=>{}) }Copy the code