I'm trying to make a loop fetching some info in an API, first I need this loop for to wait for the request to finish and after continue for the next array value, after the loop finish, then I need it to call that function again every 5 seconds, but only after the previous call ends.
Something like this:
let ids = [1, 2];
async function getInfoAPI(ids) {
for (const id of ids){
const apiInfo = await fetch(`https://apiurl/${id}`);
const infoJSON = await apiInfo.json();
//Do more things here
}
}
Now I need to call the function and wait for the loop to finish. After the loop is completed then wait for 5 seconds and call the getInfoFromAPI
function again. I tried setInterval
but if the loop, for some reason, takes more than 5 seconds to respond, the getInfoFromAPI
will be called again even if it didn't finish the previous loop.
setInterval(function(){
getInfoAPI(ids);
}, 5000);
Is there any way I could do that using promises or something like that?