promise异步处理方案

261 阅读1分钟

异步接口数据和读取缓存数据的方法封装

用法

requestCache(
    getProductList(), //接口请求的promise方法
    getCache('productList'), //读取缓存的异步方法
    (list,isCache)=>{  //获取结果数据和是否为缓存数据的方法
        //list:接口返回数据或缓存数据
        //isCache:是否为缓存数据
        this.setState(
            {list: isCache? list&&list.length!==0 ? list:null : list}
            ()=>{
                if(!isCache){
                 setCache('productList')
                }
            }
        )
    }
)

函数封装

//读取本地存储和调用接口的方法都是异步的
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=>{})
    

}