I'm calling an API which runs in for loop, but we want to wait for 1-2 seconds before hitting the API everytime inside the loop, so we made the method as async and added await before hitting the apiMethod.
But I also want to call the async method after every 5 minutes, so I added the interval method just before closing the async method. But it behaves weirdly, sometimes it waits for 5 min before invoking the method again, sometimes it calls it multiple times, and sometimes before 5 min is over. Any help ?
async fetchData(){
for(let index=0;index<rollNo[].length; index++){
await new Promise(r => setTimeout(r, 2000)); //delay of 2 sec before passing the next rollNo
//calls the service
let subscription = callAPIMethod(rollNo[index]).subscribe((data) => {
this.Response = data;
subscription.unsubscribe();
}, (error) => {
this.showToasterMessage('', 'We encountered an error', 'error');
return;
});
}
//Wait for 5 min before starting all over again
interval(300000).subscribe(x => {
this.fetchData();
});
}
I did try .pipe(delay(2000))
before making the method async but all it does is wait for 2 seconds and then run the entire for-loop at once which I don't want.
Interval or setTimeOut works only when the method is not async, but if I don't make the method as async then I can't wait for 2 seconds before hitting the API everytime.