RxJS Promise Composition (passing data)
Solution 1:
I did not read all of it, but if you want to achieve the same as pl().then(p2).then(p3).then(console.log);
, with p
being function returning promises, you could do something like (example here)
Rx.Observable.fromPromise(p1())
.flatMap(function(p1_result){return p2(p1_result);})
.flatMap(function(p2_result){return p3(p2_result);})
Or the more symmetric :
var chainedPromises$ =
Rx.Observable.just()
.flatMap(p1)
.flatMap(p2)
.flatMap(p3);
Now if you want to execute sequentially callback wrapped through fromCallback
or fromNodeCallback
, you could do something like :
function rename (flag){
return flag
? rename(file,dest).flatMap(return Rx.Observable.just(dest))
: Rx.Observable.throw(new Error('File does not exist.'));
}
Rx.Observable.just(file)
.flatMap(exists)
.flatMap(rename)
.flatMap(stat)
The latter code is untested, so keep me updated if that works.
Last comment, this should work if at each point you only have one value produced (like a promise). If you would have several files instead of one, with flatMap
you might get ordering issues (if order matters to you), so in that case, you could use concatMap
as a replacement.