简体   繁体   English

如何对每个请求进行速率限制

[英]How to rate limit a for each request

I'm calling the Webflow CMS API which has a rate limit of 60 requests per minute.我正在调用 Webflow CMS API,它的速率限制为每分钟 60 个请求。 As I have 300 items to update/create I am wondering how I can slow down my forEach to meet the rate limit:因为我有 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);
    }

I've tried await functions and setTimeout but nothing seems to work.我试过 await 函数和 setTimeout 但似乎没有任何效果。 The code powers through and hits the limit which then returns a 429 error.代码通过电源并达到限制,然后返回 429 错误。

You should maybe have a look at the axios-rate-limit module你也许应该看看 axios-rate-limit 模块

https://github.com/aishek/axios-rate-limit https://github.com/aishek/axios-rate-limit

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

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