假如有一个接口getUsersById(userId),返回用户信息的json;要求getUsersById能缓存用户信息,即同样的userId请求仅向服务器发送一次,其余从内存中获取,以提高效率。高阶要求:假设有getUsersById, getShoolInfoById, getDeviceInfoById...都需要缓存结果,提供一个通用的辅助函数。
解答:
缓存可根据实际使用场景缓存在不同的地方:
        class CacheHelper {
            constructor() {
                this.cache = new Map();
            }
            getUsersById(userId) {
                if (this.cache.has('users')) {
                    return this.cache.get('users');
                } else {
                    const data = ajax('url');
                    this.cache.set('users', data);
                    return data;
                }
            }
            getShoolInfoById(userId) {
                if (this.cache.has('shoolInfo')) {
                    return this.cache.get('shoolInfo');
                } else {
                    const data = ajax('url');
                    this.cache.set('shoolInfo', data);
                    return data;
                }
            }
            getDeviceInfoById(userId) {
                if (this.cache.has('deviceInfo')) {
                    return this.cache.get('deviceInfo');
                } else {
                    const data = ajax('url');
                    this.cache.set('deviceInfo', data);
                    return data;
                }
            }
        }
        const helper = new CacheHelper();
        console.log(helper.getUsersById());
        console.log(helper.getUsersById());









