模仿'然后'使用RxJS承诺行为

时间:2016-09-07 07:45:09

标签: javascript promise rxjs

使用Promise我可以链接以下函数:

var p = promiseFactory('1');

p.then(function(data){
    /*Do something*/
    return promiseFactory('2');
}).then(function(data){
    /*Do something else*/
    return value;
}).catch(function(err){
    /*Here I can catch all exceptions threw in then methods*/
});

我可以使用RxJS和Observable呈现此行为吗?如果是,怎么做?

1 个答案:

答案 0 :(得分:1)

您可以使用.flatMap。但是在大多数情况下,它取决于您要解决的问题。例如,考虑HTTP调用链,flatMap您可以像这样解决它



const $http = (url) => {
  return Rx.Observable.fromPromise(axios.get(url));
}

const url = 'https://jsonplaceholder.typicode.com';

const stream = $http(`${ url }/posts/1`)
  .flatMap(post => $http(`${ url }/comments?postId=${ post.data.id }`))
  .map((comments) => comments.data)
  .concatAll((comment) => comment)
  .map((comment) => comment.name)
  
stream.subscribe((res) => { 
  console.log(res);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.14.0/axios.min.js"></script>
<script src="https://npmcdn.com/@reactivex/rxjs@5.0.0-beta.7/dist/global/Rx.umd.js"></script>
&#13;
&#13;
&#13;