1
votes

Is there any way to wait for a method to finish executing before returning a value from the first observable (this.postService.addPost) ? After executing addPost to add new post, i wish to run a method to upload post image based on the added post Id and wait for this method to complete before returning a result. But with the code i written, the observable result is returned first and only executed the uploadPostImages method.

             this.postService.addPost(post).pipe(
                map((newPost: Post) => {
                    
                    if(selectedFilePaths.length !== 0) {      
                        this.imageService.uploadPostImages(newPost, selectedFilePaths);  <--wait for this to finish before return newPost
                    }

                    
                    return newPost; <-- this should execute after uploadPostImages (If selectedFilePaths not 0)
                })
            )
1
switchMap, instead of map - Ashish Ranjan

1 Answers

2
votes

Use switchMap like this

this.postService.addPost(post).pipe(
  switchMap((newPost: Post) => {
    if(selectedFilePaths.length !== 0) {      
      return this.imageService.uploadPostImages(newPost, selectedFilePaths).pipe(
        map(() => newPost),
      );
    }
    return of(newPost);
  })
)