![](/img/trans.png)
[英]How to throttle a for in Javascript loop that has an async await api call inside?
[英]How do you throttle a Javascript for loop with an API call within, in chunks of 4 calls per second?
下面是一個 AWS Lambda function (node.js),它查詢 DynamoDB,然后點擊 API 以獲取響應中的其他數據。 問題是特定的 API 每秒只允許 4 次調用,因此響應被分成 4 個塊。for 循環如何等待從塊接收每個響應,然后再移動到下一個塊以不超過 API 的限制? 換句話說,你如何限制一個帶有 API 調用的 for 循環,在進入下一個 4 個調用塊之前等待 1 秒?
exports.handler = (event, context, callback) => {
const params = {
...
};
documentClient.query(params, (err, data) => {
if (err) {
console.log(err);
callback(err);
} else {
const items = [];
const chunkSize = 4; // API allows 4 calls per second
for (let i = 0; i < data.Items.length; i += chunkSize) {
const chunk = data.Items.slice(i, i + chunkSize);
const itemChunk = chunk.map(item => {
let obj = {
...
};
axios.get('xxxxx')
.then(res => {
...
}).catch(err => {
console.log(err)
});
return obj;
});
items.push(itemChunk);
}
const flattenedItems = items.flat();
const response = {
statusCode: 200,
body: flattenedItems,
};
callback(null, response);
}
});
}
經過進一步研究,我發現了這個 node.js 庫,它可以非常簡單地限制 API 請求,我希望這可以幫助其他希望限制 API115C8885DD4A3689BE9 中的 API 調用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.