javascript - 如何对每个请求进行速率限制
问题描述
我正在调用 Webflow CMS API,它的速率限制为每分钟 60 个请求。因为我有 300 个项目要更新/创建,所以我想知道如何减慢 forEach 的速度以满足速率限制:
static update(collectionData, country, res) {
return collectionData.get()
.then(docs => {
return docs.forEach(doc => {
setTimeout(() => {
let country = doc.data();
return axios.request({
url: country.webflowId ? (webflowCollection + '/' + country.webflowId) : webflowCollection,
method: country.webflowId ? 'patch' : 'post',
headers: webflowHeaders,
data: {
"fields": {
"name": country.country,
"slug": country.country.replace(/\s+/g, '-').replace("'", "-").toLowerCase(),
"country-code": country.countryCode,
"_archived": false,
"_draft": false
}
}
})
.then(function (response) {
console.log('Updated ' + country.country + " (id: " + response.data._id + ")");
return doc.ref.set({
webflowId: response.data._id
}, {merge: true});
})
.catch(function (response) {
console.log(JSON.stringify(response));
return res.send(JSON.stringify(response));
});
});
})
.then(() => {
return res.status(200).send('Update complete!');
})
.catch(err => {
return res.status(404).send('Error listing countries: ' + err);
});
},2000);
}
我试过 await 函数和 setTimeout 但似乎没有任何效果。代码通过电源并达到限制,然后返回 429 错误。
解决方案
你也许应该看看 axios-rate-limit 模块
推荐阅读
- php - 模型如何在 Codeigniter 中保存来自控制器的数据
- c# - EF Core ICollection 不包含“包含”的定义
- java - Camel 从 FTP 读取文件并存储在本地资源文件夹中
- solr - Solr/Lucene 上下文同义词过滤器
- sql-server - 在 SQL Server / Liquibase 中,INSERT 查询是否会自动创建一个没有 CREATE 架构的表(如果它不存在)?
- mysql - ServiceStack.OrmLite:StringLengthAttribute.MaxText 产生“LONGTEXT”-如何设置为“TEXT”?
- java - Spring boot - 没有嵌入式 tomcat 的 Rest Call 客户端
- gettext - 是否有命令来标记和清除 po 文件中具有相同翻译的不同消息?
- amazon-web-services - ECS 无效参考格式错误
- firebase - Firebase web auth via Google SSO - 如何知道用户是否注册或登录