用Promise简单的实现缓存

65 阅读1分钟
const cacheMap = new Map();

function enableCache(target, name, descriptor) {
    const val = descriptor.value;
    descriptor.value = async function (...args) {
        const cacheKey = name + JSON.stringify(args);
        // 考虑时效性的逻辑判断
        // ...
        if (!cacheMap.get(cacheKey)) {
            const cacheValue = Promise.resolve(val.apply(this, args)).catch(_ => {
                cacheMap.set(cacheKey, null);
            })
            cacheMap.set(cacheKey, cacheValue);
            return cacheMap.get(cacheKey);
        }
    }
    return descriptor;
}

class Promiseclass {
    // 装饰器
    @enableCache
    static async getInfo();
}