计算发送了多少请求的简洁方法是什么?

What is a concise way of counting how many requests were sent?

我想知道如何简洁地统计发送请求数。有一个 API 允许您在一分钟内向 API 的任何端点发送最多 50 个请求。在发送第一个请求后,他们每隔 60 秒将我发送的请求数再次重置为零。 我需要做很多请求,我想知道如何才能正确跟踪它们。

async dataCollector(){
    let urlList = this.urlList; // 100+ urls
    for(let url in urlList){
      await this.getResource(url).then( data =>
        // do something with data
      )
}

现在我必须以某种方式检查 getResource() 我发送了多少请求等等,这样我就可以等待更多请求可用。检查它们的最佳方法是什么?

getResource(url){
    return this.http.get(url);
}

感谢任何建议。

您可以记录发送的请求数,以及第一个请求的时间。您还需要一种方法来等待之前的请求,这可以通过 Promise 链来完成:

 chain = Promise.resolve();
 count = 0;
 first = undefined;

 aquireSlot() {
    return this.chain = this.chain.then(async () => {
       if(this.count >= 20) {
         await timer(60_000 - (Date.now() - this.first));
         this.count = 0;
         this.first = undefined;
       }
       if(!this.first) this.first = Date.now();
       this.count += 1;
    });
 }

 async getResource(url){
   await this.aquireSlot();
   return await this.http.get(url);
 }

  // the implementation of timer is left to the reader

使用此代码,每个 getResource 调用都会在队列(承诺链)中结束。如果队列只有少于 20 个元素,则链会继续并完成调用。如果有 20 个元素,队列将暂停,直到自第一次调用后至少经过 60 秒。然后重新计数,整个过程重复。