简体   繁体   English

Javascript:速率限制但在限制结束时继续执行

[英]Javascript: Rate limit but continue execution when limit is over

I have something like this in Node.js and I'm using the Limiter to limit how many times this function can be executed in a minute.我在 Node.js 中有类似的东西,我正在使用限制器来限制该函数在一分钟内可以执行的次数。 (10 times per min for example) (例如每分钟 10 次)

  this.queue = [];
  this.limiter = new RateLimiter(10, 60000);
  someFunction() {
           for(var element of this.queue) {
                   this.limiter.removeTokens(1, (err, remainingRequests) => {
                         //do something with element in queue and remove it from queue
                    });
            }
  }

Now I want this function to run immediately after something added to the queue, if it hits the limit, it should wait until the tokens reset and then continue executing for the remaining items in the queue.现在我希望这个函数在添加到队列后立即运行,如果它达到限制,它应该等到令牌重置,然后继续执行队列中的剩余项目。 Keep in mind that items can be added to the queue all the time (assume 2 items added to the queue every sec all the time for example ).请记住,项目可以一直添加到队列中(例如,假设每秒钟有 2 个项目一直添加到队列中)。 What is the best way to achieve these results?实现这些结果的最佳方法是什么? Is there a better implementation for this or any available packages that would be helpful?对于这个或任何可用的包,是否有更好的实现?

I was able to achieve the desired results using p-queue我能够使用p-queue达到预期的结果

this.queue = new PQueue({
  concurrency: 1,
  autoStart: true,
  intervalCap: 10,
  interval: 60000 
});

this.queue.add(() => {
    this.someFunctuon();
});

someFunction() will immediately start executing once it is added to the queue. someFunction() 添加到队列后将立即开始执行。 The queue will execute 10 functions every minute.队列将每分钟执行 10 个函数。 If more functions are added, it will wait 1 min before continuing.如果添加更多功能,它将等待 1 分钟再继续。

Firstly, you should not remove elements from queue inside the for loop where you are iterating over the elements of it.首先,您不应该在 for 循环内从queue删除元素,在该循环中您正在迭代它的元素。

I want this function to run immediately after something added to the queue我希望此功能在添加到队列后立即运行

To achieve such kind of things, you should use something like BehaviorSubject要实现此类事情,您应该使用BehaviorSubject 之类的东西

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

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