简体   繁体   中英

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. As I have 300 items to update/create I am wondering how I can slow down my forEach to meet the rate limit:

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. The code powers through and hits the limit which then returns a 429 error.

You should maybe have a look at the axios-rate-limit module

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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