Search code examples
angulartypescriptangular8

Wait when all API calls finished in each For loop in Angular


I have a method named Swap(), executed for all of the selected records in the ag-grid. I am using a for loop to call the Swap method for all of them.

I want to wait about 3 seconds at the end of each loop. The code I have is like the following :

async SwapOrder(selectedRow) {
    await this.service.getOrder().subscribe(res=>{ //API call
        this.service.Action1().subscribe(res=>{ //API call
         this.service.DeleteApi(res=>{ //API call
          this.service.SwapOrder().subscribe(res={ //API call
            if(res.status==1)
               alert('success');
               });
              });
             });
           });
}

And the for loop is like the one below :

onSwap(){
     for (const selectedRow of selRows) {
         _this.SwapOrder(selectedRow);
          setTimeout(function () {
          }, 3000);
        }
}

I have seen the similar questions on SO and I changed the onSwap and for loop like below, but still the problem exists and there is no delay at the end of each loop.

 async onSwap(event, context) {
     var _this = this;
     for await (const selectedRow of selRows) {

     await  _this.SwapOrder(selectedRow);
     setTimeout(function () {}, 3000);
        } 

Added await inside for loop. After the last API call in each loop and the first API call in the next loop, must be a delay of about 3 seconds.


Solution

  • You had to return an Observable object from SwapOrder function, so that can be resolved from the onSwap function by using lastValueFrom operator.

    SwapOrder(selectedRow) {
        return forkJoin(
          this.service.getOrder(),
          this.service.Action1(),
        ).pipe(
          switchMap(([order, action1]) => this.service.DeleteApi()),
          switchMap((delete) => this.service.SwapOrder())
        );
    }
    
    async onSwap(event, context) {
      var _this = this;
      for (const selectedRow of selRows) {
         const swapOrder = await lastValueFrom(_this.SwapOrder(selectedRow));
         // if you need manual wait you can use below
         // await lastValueFrom(timer(3000));
         if (swapOrder.status === 1) {
           alert("success");
         }
      }
    }