我正在尝试处理每次循环时要调用的3个受限制的API端点。我试图确保每次调用之间有500毫秒的延迟,所以我不会发出太多请求,相反,发生的事情是等待500毫秒*迭代次数后所有的调用都会发生,请求限制返回429。
我要做的是创建我认为会是一个简单的等待函数的函数,但是它没有用,所以我着手研究这个问题。我发现的几乎所有解决方案都是相同类型的函数,要么忽略等待,要么执行我现在正在经历的事情,或者建议使用我要避免的第三方依赖,因为这是我唯一要做的事情我的代码。现在,我有了一个新的等待功能,并根据研究进行了稍微修改。这是我当前的代码:
// wait function
async function wait(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
// one of 3 identical api calls (except the endpoint changes, in this case I've filled it with
example.com)
function callAPI(param) {
return fetch (`https://example.com?param=${param}`)
.then(res => {
if (res.ok) {
return res.json();
}
});
}
// Iteration
async function getEach(arr) {
arr.forEach(async name => {
await wait(500);
await callAPI(name);
// then api call 2, 3
// then return, console log, append to obj or array, w.e. with the api results
});
}
getEach(arrList);
我希望找出的是:
谢谢
Array.forEach不会等待wait()和callAPI()调用完成,因此将很快连续调用它们。但是,您可以使用for ..循环或仅for循环轻松地执行此操作。
例如:
async function getEach(arr) {
for(let name of arr) {
await wait(500);
await callAPI(name);
}
}
要么
async function getEach(arr) {
for(let i = 0; i < arr.length; i++) {
await wait(500);
await callAPI(arr[i]);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句