Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

500
Views
Angular 12/Typescript/rxjs: error handling of nested Promises and rxjs Observable

I have a mix of nested Promises and subscriptions, and I simple want to do the following:

  • Call my function bar() and understand if it was fully successfully, or if an error occurred

current approach: Currently my bar() returns a boolean Observable, and I handle each error separately, for Promise via .catch, for the rxjs Observable via the error handle:

    foo(): void {
       this.bar.subscribe((data: boolean) => console.log('the function call bar() was ' + data));
    }

    bar(): Observable<boolean> {
    let subject = new Subject<boolean>();
    
        this.httpHandler.newFoo().subscribe(
        (data) => 
          this.bar(data)
            .then((barData) => 
              this.httpHandler.updateBar().subscribe(
                (barData2) => subject.next(true),
                (error) => subject.next(false)))
            .catch(err => subject.next(false)),
        (error) => subject.next(false));

        return subject.asObservable();
    }

Apparently this is messy, and looks like an overkill for the simple purpose to understand if the bar() function call finished without any errors. Is there a better way to handle nested errors altogether?

Thanks in advance

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I think this could be succinctly written as:

this.httpHandler.newFoo().pipe(
  switchMap(data =>
    from(this.bar(data)).pipe(
      switchMap(() =>
        this.httpHandler.updateBar().pipe(
          mapTo(true)
        )
      )
    )
  ),
  catchError(() => of(false))
)

To make an observable out of a promise, use from(). Use switchMap() to transition between observables. Then it's just a matter of chaining your calls:

this.httpHandler.newFoo() -> this.bar() -> this.httpHandler.updateBar()

and returning true in the end, otherwise false for any error.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!