繁体   English   中英

es6中的缓存方法调用结果

[英]cache method call results in es6

是否可以在es6中缓存方法调用结果,如何正确完成?

示例es2015:

Helper.prototype.getCount = function (requestURL) {
    var cache = Helper.prototype.getCounters.cache,
        result = '';

    if (cache[requestURL] === undefined) {
        result = doSomething();
    } else {
        // if result wild in cache -> load it
        result = cache[requestURL];
    }

    return result;

    function doSomething() {
        var result = 1; // ... some havy operations

        // save results in cache
        cache[requestURL] = result;

        return result;
    }
}

Helper.prototype.getCounters.cache = {};

我正在寻找类似的东西,但是在es6中。

class Helper {
    getCount(url) {
       //...
    } 
}

感谢帮助!

缓存返回值以避免不必要的密集操作是一个好主意。 在OOP中进行缓存的最常见情况是,您需要从工厂类中创建很多相似的对象。 这实际上是GoF模式(请参阅Flyweight )。

就您而言,如果我很了解您的问题,那么您正在尝试使用缓存来避免无用的AJAX调用。 使用ES6,我认为一个好的实现可能涉及Map用于缓存,而Promise用于更好的异步处理。 在以下使用GitHub API的实现中, ajax是静态方法, getUser是原型属性,而cache是静态属性。

 class GitHub { static ajax(username) { return new Promise((resolve, reject) => { let req = new XMLHttpRequest(); req.onreadystatechange = function () { if (this.readyState === XMLHttpRequest.DONE) { if (this.status === 200) { let json = JSON.parse(this.responseText), user = { name: json.name, bio: json.bio }; GitHub.cache.set(username, user); resolve(user); } else { reject(new Error(`${this.status} ${this.statusText}`)); } } }; req.open('GET', `https://api.github.com/users/${username}`, true); req.send(null); }); } getUser(username = 'Badacadabra') { if (!GitHub.cache.has(username)) { console.log('AJAX'); return GitHub.ajax(username); } else { console.log('Cache'); return GitHub.cache.get(username); } } } GitHub.cache = new Map(); let github = new GitHub(); github.getUser() .then(console.log) .then(() => github.getUser()) .then(console.log) .then(() => github.getUser()) .then(console.log) .catch(console.error); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM