Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

513
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda