in my project, I am having one challenge. ie.. I need to call multiple API calls one by one. Here I am using RxJS flatMap
operator for that. it is working expected. but my additional requirement is I need to set 10 seconds delay for every API call. I have used 'throttle' operator but It is not working.I have attached my code below. can anyone tell us what I did wrong in my code.
public makeSubmitAPI(oncallData): Observable<any> {
let orderPayload = this.postAPIService.prepareOrderPayload(oncallData);
let url = "";
let orderResponse: any;
return this.apiCallsService.apiCall('placeOrder', orderPayload, 'post', false)
.map((orderRes: any) => {
orderResponse = orderRes;
url = `orders/${orderResponse.data.id}/progress`;
let progressPayload = this.postAPIService.prepareProgressAPIData(oncallData, orderResponse.data, this.userType);
return progressPayload;
}).pipe(throttle(val=> interval(5000)))
.flatMap(progressPayload => {
return this.apiCallsService.apiCall(url, progressPayload, 'post', false).pipe(throttle(val=> interval(5000)))
})
.flatMap(progressResponse => {
return Observable.combineLatest(
orderResponse.data.serviceAddresses.map((address, index) => {
let fullfilledAPI = this.postAPIService.prepareFullfilledAPIData(oncallData, orderResponse.data, progressResponse, this.userType, index, orderPayload);
return this.apiCallsService.apiCall('fullfillment', fullfilledAPI, 'post', false).map(res => res);
})
)
});
}
Thanks
To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds.
Using setTimeout() We can pass an API call inside the setTimeout() to execute it after a certain delay. const res = await fetch(`https://jsonplaceholder.typicode.com/posts`); }, 2000); Once this timer is created, it will send the API request after two seconds.
Create a Simple Delay Using setTimeout The standard way of creating a delay in JavaScript is to use its setTimeout method. For example: console.log("Hello"); setTimeout(() => { console.log("World!"); }, 5000); This would log “Hello” to the console, then make JavaScript wait 5 seconds, then log “World!”
The setTimeout() method calls a function after a number of milliseconds. 1 second = 1000 milliseconds.
You can use concatMap
(instead of the flatMap
that wrapps the API call) to make the calls one after another and then delay()
to force that 5s delay you want:
.concatMap(progressPayload => this.apiCallsService.apiCall(url, progressPayload, 'post', false)
.pipe(
delay(5000)
)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With