异步缓存-cacheCall

缓存是提高性能的一个法宝,在异步的世界里也需要有缓存,因此我写了一个异步缓存的闭包函数,此函数的功能为在指定的时间interval内如果参数相同只执行一次http请求,如果在interval内发生并发,则缓存并发请求等待请求返回后一并处理

 //异步缓存
 var cacheCall=function (fn, interval) {
     var caches = [],cacheToken;
     setInterval(function () {
         lib._.remove(caches, function (cache) {
             return !cache.pending && new Date() - cache.time > interval;
         });
     }, 60 * 1000);
     return function (arg, cb) {
         var getCache = function () {
             return lib._.find(caches, function (cache) {
                 return lib._.isEqual(cache.arg, arg);
             });
         }
         var done = function (res) {
             var cache = getCache();
             lib._.assign(cache, { value: res, time: new Date(), pending: false });
             lib._.remove(cache.list).forEach(function (cb) { cb(res); });
         }
         var cache = getCache();
         if (cache) {
             cache.pending ? cache.list.push(cb) : cb(cache.value);
         } else {
             caches.push({arg:arg, pending: true, list: [cb] });
             fn(arg,done);
         }
     }
 },

测试

     var f = cacheCall(function (args, cb) { console.log(args); cb(args); }, 1000 * 60);
     f('1', function () { console.log('a') });
     f('1', function () { console.log('a') });
     f('2', function () { console.log('b') });

输出:

1

a

a

2

b

可以看到对于相同的参数调用只输出了一次

注:lib._为lodash库

posted @ 2017-06-21 10:20  朱现国  阅读(1297)  评论(0编辑  收藏  举报