Search code examples
typescriptecmascript-6async-awaitobservablees6-promise

Making multiple http calls inside foreach loop async


Lets say I have a foreach loop

  Object.keys(this.treeMap).forEach(id=>{
    this.getSelectionById(id);
  })
  this.processAfterHttpCalls();

and getSelectionById method makes an http call

  getSelectionById(id){
      let requestBody = {
        id: id
      };
      this.subscription = this.dependenciesService.getInstancesByCSIId(requestBody)
        .subscribe(data => {
          this.someProcessing(data);
        }, err => {
          this.appMessageService.showMessage(this.appMessageService.ERROR, err);
        })
    }

But is there a way i can make those call async so once call the http calls inside the forEach block have been finished, I can call another method?


Solution

  • if your getSelectionById returns an observable :

    getSelectionById(id){
        let requestBody = {
            id: id
        };
        return this.dependenciesService.getInstancesByCSIId(requestBody)
            .pipe(map(data => this.someProcessing(data));
    }
    

    You can zip all http calls inside an single observable :

    zip(...Object.keys(this.treeMap).map(id=> this.getSelectionById(id)))
        .subscribe(_ => this.processAfterHttpCalls(), err => this.appMessageService.showMessage(this.appMessageService.ERROR, err));
    

    This way all http calls are made in parallel, and the processAfterHttpCalls is called when all http calls have finished.