2016-09-07 17 views
2

との約束の振る舞いは、私は以下のような機能をチェーンすることができます?エミュレート「は、」約束してRxJS

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と観察可能で、この動作をレンダリングすることはできますか?

+1

'.flatMap'を使用できます。実際には、解決したい問題に依存します。 –

答えて

1

あなたは.flatMapを使用することができます。しかし、ほとんどの場合、それはあなたが解決したいですか問題に依存します。例えばflatMapと、チェーン呼び出し、HTTP考えるあなたはこの

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/[email protected]/dist/global/Rx.umd.js"></script>
のようにそれを解決することができます

+1

もちろん、これは「Promise.then」よりも実質的に強力です。 'Promise.then'は単一の値をとり、それを単一の値を生成する新しい' Promise'を返す関数にマップします。 'Observable.flatMap'は、0以上(潜在的には無制限)の値のストリームを取り、それぞれを0以上(潜在的には無制限)の値に展開します。これは非常に便利ですが、Promiseのデータは単一の機能で簡単に処理できますが、折り返し、スキャンしたり、Rxで使用可能な形式に縮小したりする必要があります。 – Jules