问题
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
orusing
) - 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