0

I have a popular scenario where I need to create one promise that returns data which is fed to a second promise. If the first promise fails, I need to cancel the second promise. In 'Promise' land it would look something like this:

Fn1.doPromise( initialData )
  .then(info => {
        Fn2.doPromise( info )
              .then(result => {
                  //success - return result
              })
              .catch(error => {
                //error
              });
  })
.catch(error => {
  //cancel 2nd promise and show error
});

Now I am trying to learn the best way to do this using Observables with something like RxJS. Can anyone give me a good solution ? Thank in advance !

user3743222
  • 18,345
  • 5
  • 69
  • 75
29er
  • 8,595
  • 12
  • 48
  • 65

2 Answers2

1

The general issue of error handling with RxJS is dealt with here. Main points are :

  • Catching Errors (with catch operator, either at instance level or at class level)
  • Ignoring Errors with onErrorResumeNext
  • Retrying Sequences (with retry)
  • Ensuring Cleanup (with finally)
  • Ensuring Resource Disposal (with finally or using)
  • Delaying Errors (with mergeDelayError)

About your specific question you can use Rx.Observable.fromPromise to convert a promise into an observable; Rx.Observable.prototype.catch to catch errors as they occur.

Rx.Observable.fromPromise(Fn1.doPromise( initialData ))
  .flatMap(info => {
        return Rx.Observable.fromPromise(Fn2.doPromise( info ))
              .flatMap(result => {
                  //success - return result
                  // !! You must return an observable or a promise here !!
              })
              .catch(error => {
                //error
                // !! You must return an observable here !!
              });
  })
.catch(error => {
  //cancel 2nd promise and show error
  // !! You must return an observable here !!
});

Examples :

user3743222
  • 18,345
  • 5
  • 69
  • 75
0

I was also able to find a nice generic solution for my promise 'chaining' after doing some more research. With this I can use an many promises as I need.

const flatMapAll = (...fns) =>
   fns.reduce((acc, fn) =>
   acc.flatMap(fn), Rx.Observable.just())



flatMapAll( p1 ,p2 ,p3).subscribe();
29er
  • 8,595
  • 12
  • 48
  • 65
  • I guess you refer to another one of my answers : http://stackoverflow.com/questions/34701304/rxjs-promise-composition-passing-data/34701912#34701912. It would be nice if you property quote it in your answer so other users arriving here from a google search can also have a look at it to get some context and extra explanations. Also note that with that solution, you renounce the option to have an inner error handler as you had in your question and you do not address the issue of error propagation. – user3743222 Jan 22 '16 at 21:00