缓存是提高性能的一个法宝,在异步的世界里也需要有缓存,因此我写了一个异步缓存的闭包函数,此函数的功能为在指定的时间interval内如果参数相同只执行一次http请求,如果在interval内发生并发,则缓存并发请求等待请求返回后一并处理
1 //异步缓存 2 var cacheCall=function (fn, interval) { 3 var caches = [],cacheToken; 4 setInterval(function () { 5 lib._.remove(caches, function (cache) { 6 return !cache.pending && new Date() - cache.time > interval; 7 }); 8 }, 60 * 1000); 9 return function (arg, cb) { 10 var getCache = function () { 11 return lib._.find(caches, function (cache) { 12 return lib._.isEqual(cache.arg, arg); 13 }); 14 } 15 var done = function (res) { 16 var cache = getCache(); 17 lib._.assign(cache, { value: res, time: new Date(), pending: false }); 18 lib._.remove(cache.list).forEach(function (cb) { cb(res); }); 19 } 20 var cache = getCache(); 21 if (cache) { 22 cache.pending ? cache.list.push(cb) : cb(cache.value); 23 } else { 24 caches.push({arg:arg, pending: true, list: [cb] }); 25 fn(arg,done); 26 } 27 } 28 },
测试
1 var f = cacheCall(function (args, cb) { console.log(args); cb(args); }, 1000 * 60); 2 f('1', function () { console.log('a') }); 3 f('1', function () { console.log('a') }); 4 f('2', function () { console.log('b') });
输出:
1
a
a
2
b
可以看到对于相同的参数调用只输出了一次
注:lib._为lodash库