异步缓存-cacheCall

本文介绍了一个异步缓存闭包函数的设计与实现,该函数能够在指定时间内避免重复HTTP请求,有效提升性能。通过使用lodash库,该函数能够缓存并发请求并在首次请求返回后批量处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

缓存是提高性能的一个法宝,在异步的世界里也需要有缓存,因此我写了一个异步缓存的闭包函数,此函数的功能为在指定的时间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库

转载于:https://www.cnblogs.com/zhuxianguo/p/7058233.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值