使用 RxJs Observable 包装基于 Promise 的 JavaScript HTTP 客户端 [英] Wrapping Promise based JavaScript HTTP client with RxJs Observable

查看:59
本文介绍了使用 RxJs Observable 包装基于 Promise 的 JavaScript HTTP 客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑使用 Observables 添加 .flatMapLatest() &基于 Promise 的 HTTP 客户端库 (axios) 的 .throttle() 功能.但我不会改变整个应用程序以使用 Observables,所以我需要这样的东西:

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

Promise -> Observable -> Promise

有人做过这样的事情吗?我发现的所有示例都没有做到这一点.

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

我知道 RxJs 提供了一种从 Promise 生成 Observable 然后将其转换回 Promise 的方法,但我还没有想出如何将其应用于由随机后续 HTTP 客户端调用创建的多个 Promise.

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.

推荐答案

Observables 会自动同化 promise.你可以在 RxJS 调用中使用它们,它会正常工作":

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 和 promises 与 .toPromise 在 observables 和 observables 自动消耗 promises 上很好地混合和匹配.您可以安全地混合搭配它们.

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

请记住,RxJS 不知道承诺库取消 - 所以如果你依赖它,你必须手动完成.

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

这篇关于使用 RxJs Observable 包装基于 Promise 的 JavaScript HTTP 客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆