RxJS sequence equivalent to promise.then()?

前端 未结 8 1400
南旧
南旧 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:23

    A more modern alternative:

    import {from as fromPromise} from 'rxjs';
    import {catchError, flatMap} from 'rxjs/operators';
    
    fromPromise(...).pipe(
       flatMap(result => {
           // do something
       }),
       flatMap(result => {
           // do something
       }),
       flatMap(result => {
           // do something
       }),
       catchError(error => {
           // handle error
       })
    )
    

    Also note that for all this to work, you need to subscribe to this piped Observable somewhere, but I assume it's handled in some other part of the application.

提交回复
热议问题