Walter White
Walter White

Reputation: 1026

Wait untill observable complete

map((tasks): any => {
  return tasks.map(task => ({
      ...task,
      status: this.getStatus(task.owner, task.delegationState, task.assignee, task.id),
  }));
});

I call getStatus method inside map() rxjs operator

getStatus(
  owner: string | null, 
  delegationState: string | null, 
  assignee: string | null, 
  id: string): string {

  if (assignee) {
      if (!owner) {
          if (!delegationState) {
              this.caseService.getUserOperationHistory({
                  taskId: id,
                  entityType: 'T',
                  operationType: 'Claim',
              }).subscribe((res) => {
                  return 'Claimed';
              });
          } else {
              return 'Assigned';
          }
      }

      if (delegationState === 'PENDING') {
          return 'Delegated';
      }
      if (delegationState === 'RESOLVED') {
          return 'Assigned';
      }
  }

  return 'Unassigned';
}

When I execute async code getUserOperationHistory() the code is executed synchronously so instead return 'Claimed' as a result of getUserOperationHistory() it returns 'Unassigned' how to wait till async code is completed?

Upvotes: 0

Views: 95

Answers (1)

AVJT82
AVJT82

Reputation: 73337

I would use forkJoin for the nested calls, returning something from outside subscribe will most likely never have the correct value. So I would suggest something like:

switchMap((tasks: any) => forkJoin(tasks.map(task => 
    this.getStatus(...).pipe(
      map(data => ({...task, status: data}))
    )
  )
);

If getStatus returns only the string, then you can use of('stringHere') to return an observable.

And please do not use any, type your data, it will help you in future!

Upvotes: 2

Related Questions