【发布时间】:2020-08-27 22:56:29
【问题描述】:
我正在尝试处理每次通过循环时要调用的 3 个受限制的 API 端点。我试图确保每次调用迭代之间有 500 毫秒的延迟,所以我不会发出太多请求,而是在等待 500 毫秒 * 迭代次数后发出所有调用,这当然会达到请求限制返回 429。
我所做的是创建了一个我认为很简单的等待函数,但它不起作用,所以我开始搜索这个问题。我发现的几乎每个解决方案都是相同类型的函数,它要么忽略等待,要么执行我现在正在经历的事情,或者建议使用我正在避免的第 3 方依赖项,因为这是我唯一这样做的地方我的代码。现在我有了一个新的等待功能,根据研究稍作修改。这是我当前的代码:
// 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);
我希望知道的是:
- 了解为什么这不符合我的想法
- 如何达到我想要的结果
谢谢
【问题讨论】:
-
非常类似于这个问题:stackoverflow.com/questions/37576685/…
-
@Wyck 似乎解决方案与问题的原因相同,但感知的问题是不同的
标签: javascript api