Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

502
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda