Wrapping Promise based JavaScript HTTP client with RxJs Observable

谁都会走 提交于 2021-01-28 01:48:01

问题


I was thinking of using Observables to add .flatMapLatest() & .throttle() functionality to a Promise based HTTP client library (axios). But I'm not going to change the whole application to work with Observables, so I would need something like this:

Promise -> Observable -> Promise

Anyone managed to do something like this? None of the examples I've found do exactly that.

I know that RxJs provides a way to make an Observable from Promise and then convert it back to Promise, but haven't figured out how I could apply that to multiple Promises created by random subsequent HTTP client calls.


回答1:


Observables will automatically assimilate promises. You can just use them inside RxJS calls and it'll "just work":

myObservable.flatMap(x => somePromiseReturningFn("/api/" + x))

Will do exactly what you'd like it to.

Observables and promises mix and match nicely with .toPromise on observables and observables consuming promises automatically. You can safely mix and match them.

Just remember RxJS is not aware of promise library cancellation - so if you're relying on that you'd have to do it manually.




回答2:


RXJS has a good pattern for this.

Observable.fromPromise(somePromiseReturningThing)

This is much better than the flatmap pattern above as the flatmap operates on error or legitimate return equally. Treat this obserable with your

Observable.fromPromise(aPromise)
  .map(..)
  .catch(..)

etc.



来源:https://stackoverflow.com/questions/34612746/wrapping-promise-based-javascript-http-client-with-rxjs-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!