Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

javascript - Observable - converting 2 promises into an observable

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 !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 :


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...