【发布时间】:2020-09-09 07:42:56
【问题描述】:
我有一个 API,它限制了我每分钟可以向该 API 提供的任何端点发送多少请求(50/分钟)。
在以下代码部分中,我使用 URL 作为属性过滤对象 orders,每个具有提供数据的 URL 的对象都应存储在我的 app.component.ts 中的 successfullResponses 中。
Promise.all(
orders.map(order => this.api.getURL(order.resource_url).catch(() => null))
).then(responses => {
const successfulResponses = responses.filter(response => response != null)
for(let data of successfulResponses) {
// some other requests should be sent with data here
}
});
要检查的orders 超过50 个,但我一次最多只能检查50 个orders,所以我尝试在我的服务中处理它。我在发送第一个请求时设置了第一个日期。之后,我将新请求的日期与第一个请求的日期进行比较。如果差值超过 60,我将当前日期设置为新日期,并将 maxReq 再次设置为 50。如果小于 60,我检查是否还有请求,如果是,我发送请求,如果没有,我只是等一分钟:
sleep(ms){
return new Promise(resolve => setTimeout(resolve, ms));
}
async getURL(){
if(!this.date){
let date = new Date();
this.date = date;
}
if((new Date().getSeconds() - this.date.getSeconds() > 60 )){
this.maxReq = 50;
this.date = new Date();
return this.http.get(url, this.httpOptions).toPromise();
} else {
if(this.maxReq > 0){
this.maxReq -= 1;
return this.http.get(url, this.httpOptions).toPromise();
} else{
console.log("wait");
await this.sleep(60*1000);
this.maxReq = 50;
this.date = new Date();
return this.http.get(url, this.httpOptions).toPromise();
}
}
}
但是app.component.ts 中的代码并没有等待函数getURL() 并使用请求执行进一步的代码,这导致了我发送“请求太多太快”的问题。
我该怎么办?
【问题讨论】:
标签: javascript angular typescript api asynchronous