RxJS sequence equivalent to promise.then()?

前端 未结 8 1408
南旧
南旧 2020-11-28 05:12

I used to develop a lot with promise and now I am moving to RxJS. The doc of RxJS doesn\'t provide a very clear example on how to move from promise chain to observer sequenc

8条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 05:19

    For data flow (equivalent to then):

    Rx.Observable.fromPromise(...)
      .flatMap(function(result) {
       // do something
      })
      .flatMap(function(result) {
       // do something
      })
      .subscribe(function onNext(result) {
        // end of chain
      }, function onError(error) {
        // process the error
      });
    

    A promise can be converted into an observable with Rx.Observable.fromPromise.

    Some promise operators have a direct translation. For instance RSVP.all, or jQuery.when can be replaced by Rx.Observable.forkJoin.

    Keep in mind that you have a bunch of operators that allows to transform data asynchronously, and to perform tasks that you cannot or would be very hard to do with promises. Rxjs reveals all its powers with asynchronous sequences of data (sequence i.e. more than 1 asynchronous value).

    For error management, the subject is a little bit more complex.

    • there are catch and finally operators too
    • retryWhen can also help to repeat a sequence in case of error
    • you can also deal with errors in the subscriber itself with the onError function.

    For precise semantics, have a deeper look at the documentation and examples you can find on the web, or ask specific questions here.

    This would definitely be a good starting point for going deeper in error management with Rxjs : https://xgrommx.github.io/rx-book/content/getting_started_with_rxjs/creating_and_querying_observable_sequences/error_handling.html

提交回复
热议问题