本文介绍了可观察的-将2个诺言转换为可观察的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个流行的场景,我需要创建一个承诺,该承诺返回返回到第二个承诺的数据.如果第一个承诺失败,我需要取消第二个承诺.在承诺"土地上,它看起来像这样:

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

现在,我正在尝试使用Observables和RxJS之类的方法来学习最佳方法.谁能给我一个好的解决方案?预先感谢!

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 !

推荐答案

RxJS处理错误的一般问题由此处.要点是:

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

  • 捕获错误(使用catch运算符,无论是在实例级别还是在类级别)
  • 使用onErrorResumeNext
  • 忽略错误
  • 重试序列(使用retry)
  • 确保清理(使用finally)
  • 确保资源处置(使用finallyusing)
  • 延迟错误(使用mergeDelayError)
  • 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)

关于您的特定问题,您可以使用 Rx.Observable.fromPromise 将诺言转换为可观察的; Rx.Observable.prototype.catch 在发生错误时及时捕获.

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 !!
});

示例:

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

这篇关于可观察的-将2个诺言转换为可观察的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:25