Observable - converting 2 promises into an observable

徘徊边缘 提交于 2019-12-12 02:39:17

问题


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 !


回答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 :

  • first error handler activated
  • no error
  • inner error handler activated



回答2:


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();


来源:https://stackoverflow.com/questions/34951787/observable-converting-2-promises-into-an-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!