Wang Gang ReactNative 9-- development project combat three of offline caching mechanism and promise

The first offline caching mechanism and promise,
promise mechanisms:
1, solve the callback prison,
2, promise two results: do it (resolve) and can not (reject)
First access the local cache, the local cache is empty on access network; access to the network to do in the local cache; let's implement these logic

/**
 * Created by penn on 2016/12/21.
 */

import {
    AsyncStorage,
} from 'react-native';

export default class DataRepository {
    constructor() {
    }
    saveRepository(url, data, callback) {
        //如果data或者url不为空
        if (!data || !url)return;
        //把请求得到的数据缓存到本地,并记录缓存时间
        let wrapData = {data: data, update_date: new Date().getTime()};
        // 1,缓存到本地
        // 2,JSON.stringify(wrapData):把对象转换为字符串;
        AsyncStorage.setItem(url, JSON.stringify(wrapData), callback);
    }

    fetchRepository(url) {
        return new Promise((resolve, reject)=> {
            //1,可以理解为在子线程中运行这些代码
            //2,先从本地获取
            //3,只要返回一个Promise对象,那后面肯定跟着then方法;fetchLocalRepository返回
            //的结果,最终传给了后面的then方法。
            this.fetchLocalRepository(url).then((wrapData)=> {
                 //1,wrapData是从本地取到的,如果不为空就执行 resolve(wrapData.data, true);
                if (wrapData) {
                    //1,如果wrapData不为空,就说明本地有数据,本地有数据就从本地获取数据
                    //2, {data: data, update_date: new Date().getTime()};缓存的时候我们把数据丢到data这个键值对里,
                    // 所以这里要取数据的话也要写wrapData.data
                    resolve(wrapData.data, true);
                } else {//为空就是本地没有数据,没数据就去请求网络
                    //凡是返回Promise,后面肯定要加一个then()方法;
                    this.fetchNetRepository(url).then((data)=> {
                        resolve(data);
                    }).catch((error)=> {
                        reject(error);
                    })
                }
                //承诺失败
            }).catch((error)=> {
                this.fetchNetRepository(url).then((data)=> {
                    resolve(data);
                }).catch((error=> {
                    reject(error);
                }))
            })
        })
    }
    fetchLocalRepository(url) {
        return new Promise((resolve, reject)=> {
            //1,使用AsyncStorage做缓存,可以把AsyncStorage当做android中的SharedPrefrece;
            //2,获取缓存数据、
            //3,键使用url地址
            AsyncStorage.getItem(url, (error, result)=> {
                //1,如果没有发生异常
                //2,一般情况下error是为空的。发生错误的时候才不为空
                if (!error) {
                    try {
                        //在这里给Promise赋值
                        resolve(JSON.parse(result));
                    } catch (e) {
                        reject(e);
                        console.error(e);
                    }
                } else {
                    reject(error);
                    console.error(error);
                }
            })
        })
    }
    fetchNetRepository(url) {
        return new Promise((resolve, reject)=> {
                fetch(url)
                    //把response转化为json字符串
                    .then((response)=>response.json())
                    //如果这个时候没有网络,就会回调catch方法。
                    .catch((error)=> {
                        reject(error);
                    }).then((responseData)=> {//如果成功了
                    if (!responseData) {
                        //如果responseData没有取到数据,我们就认为它失败了
                        reject(new Error('responseData is null'));
                        return;
                    }
                    resolve(responseData);
                    //缓存到本地
                    this.saveRepository(url,responseData)
                }).done();
        })
    }
    checkDate(longTime) {
        let currentDate = new Date();
        let targetDate = new Date();
        targetDate.setTime(longTime);
        if (currentDate.getMonth() !== targetDate.getMonth())return false;
        if (currentDate.getDate() !== targetDate.getDate())return false;
        if (currentDate.getHours() - targetDate.getHours() > 4)return false;
        if (currentDate.getMinutes() - targetDate.getMinutes() > 1)return false;
        return true;
    }
}

transfer:

var dataRepository = new DataRepository();
  //获取网络数据
        //承诺无论成功还是失败都会走到then方法,
        dataRepository.fetchRepository(`http://192.168.1.111:8090/weixinapp/studentinfo/reactlist`)
        //result就是承诺包含里面的东西,result就是返回的东西
            .then(result=>{
                this.setState({
                    //我们拿到了result对其进行赋值
                    dataList:result,
                    content:result[0].mainTitle,
                    isLoading:false
                })

Download complete item code
https://download.csdn.net/download/qczg_wxg/11107525

Guess you like

Origin blog.csdn.net/qczg_wxg/article/details/89220064