Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute http request sequentially in Angular 6

I need to send multiple HTTP PUT request to server sequentially (after the next request is only started after completing the previous request, the number of request is not fixed). If I use the below source code, all request will be sent

 `listURL.forEach(url => {
    const req = new HttpRequest('PUT', url, formData, { reportProgress: true});
    httpClient.request(req).subscribe(event=>{});
  });`

Is there anyway to execute the requests sequentially?

like image 280
Waveter Avatar asked Nov 19 '25 10:11

Waveter


2 Answers

You could use async/await with Promise to stream line this. Convert the observable to a promise using toPromise()

async doSomethingAsync() {
    for(let url of listURL) {
        const req = new HttpRequest('PUT', url, formData, { reportProgress: true});
        const result = await httpClient.request<ModelHere>(req).toPromise();
        // do something with result
    }
}

For more on async/await see also this excellent answer and scroll to the heading ES2017+: Promises with async/await.

like image 112
Igor Avatar answered Nov 22 '25 00:11

Igor


use reduce and switchMap :

['url 1', 'url 2'].reduce((acc, curr) => acc.pipe(
  mergeMap(_ => this.mockHttpCall(curr)),
  tap(value => console.log(value)),
), of(undefined)).subscribe(_ => console.log('done !'));

Stackblitz


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!