Q: Await for a subscription inside a forEach to finish I'm using angular and I need to emit a new event when my for each finishes the post requests for every element.
the elements are users and for each one I need to make a post request to register them on my server. 
This is my code:
export class CustomerBulkImport {
@Output() customersAdded = new EventEmitter<boolean>();
...
...
registerCustomers(){

  let usersRegistered = this.records.forEach( customer=>{
    customer.owner = this.owner

     this.service.register(this.strategy,customer).subscribe((res:NbAuthResult)=>{

      this.submitted = true;
      if (res.isSuccess()) {
        this.messages = res.getMessages();
        this.tokenStorage.set(this.currentToken)
      } else {
        this.errors = res.getErrors();
      }
      this.cd.detectChanges();
    })
  });


  this.customersAdded.emit(true)
  console.log('emitted')

 }
}

As you can see here, my console.log('emitted') is executing before the forEach ends.


A: This is because of asynchronous nature of observables. you can use forkjoin to hit multiple parallel calls and subscribe to them so that you can know when all have completed.
registerCustomers(){
let myCalls = this.records.map((customer) => {
  customer.owner= this.owner;
  return this.service.register(this.strategy, customer).pipe(map(res:NbAuthResult) => {
      this.submitted = true;
      if (res.isSuccess()) {
        this.messages = res.getMessages();
        this.tokenStorage.set(this.currentToken)
      } else {
        this.errors = res.getErrors();
      }
      this.cd.detectChanges();
  }));
});
forkJoin(myCalls).subscribe(() => {
  this.customersAdded.emit(true)
  console.log('emitted')
});
} 

