• 异步缓存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库

  • 相关阅读:
    【CCPC2020网络赛11】Convolution
    【CCPC2020网络赛02】Graph Theory Class
    全国中学生网安竞赛出题总结
    XDU2020ACM校赛总结
    CTF错误集合
    【洛谷2916】图的遍历
    20200420(ABC)题解 by 辛晓东
    20200402(ABC)题解 by 孙晨曦
    20200406(ABC)题解 by 徐光旭
    20200407(DE)题解 by 孙晨曦
  • 原文地址:https://www.cnblogs.com/zhuxianguo/p/7058233.html
Copyright © 2020-2023  润新知