I am trying to deal with 3 throttled API endpoints that I want to call each time I go through a loop. I'm trying to make sure there is a 500ms delay between each iteration of calls so I don't make too many requests, instead what happens is it makes all the calls after waiting 500ms * the number of iterations, which of course hits the request limit returning a 429.
What I've done is create what I thought would be a simple wait function, but it did not work so I set about to googling the problem. Almost every solution I've found has been the same type of function, which either ignores the wait, or does what I am experiencing now, or suggests using a 3rd party dependency which I am avoiding since this is the only place I do this in my code. Now I have a new wait function, slightly modified based on research. Here is my current code:
// 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);
What I'm hoping to find out is:
- Understanding why this is not behaving the way I think it should be
- How to achieve my desired results
Thanks