Should I always use Observables where a promise can be used?

℡╲_俬逩灬. 提交于 2020-04-13 14:51:35

问题


I posted a question on stack overflow yesterday where I asked the userbase if there was a way to await the result of an async operation without explicitly using the async and await keywords. The reason being that I needed to wait for the operation to complete so that I could use the value returned before any other HTTP requests could be fired. It turns out there was, it involved using observables to subscribe to the result of the operation, and to then use a mergeMap to continue on with the other requests.

I also read an article the other day that outlined that a lot of JS/RxJs/Angular developers were 'abusing' observables by using them for every possible async operation, even where there was only a single value being returned. The article outlined that in this particular case promises would be more suitable, as observables were seen to be overkill.

This has got me wondering if there is any particular scenarios or reasons where I should be using promises over observables. In my own opinion observables offer much greater control over an async operation and also provide far much functionality through the use of the let-able operators provided by RxJS. This, combined with the fact that async operations that only return a single value can still be handled just as well by Observables (since they're simply a stream that only has a single value) makes me think that there really isn't a particular scernario where I would ever want to use a promise over an observable. Does such a scenario exist?

I hope this question isn't too subjective, as the advantages and disadvantages or promises and observables are both objective properties of the two programming constructs. So hopefully I shouldn't see this question closed.


回答1:


As an Angular developer I don't like to see promises being used as we are building applications built on observables in a reactive programming style.

There is no abusing observables because a promise could be used instead.

The Angular http service could use promises as a http a request is a fire and get a single response scenario, not a stream but an observable still makes complete sense in this case.

I would argue that why bring promises into a reactive programming application when we already have observables for async operations.

I am 100% of the opinion that Angular devs are definitely not abusing observables in a uses case where a promise could be used. Using a single async style is more consistent that a mix and match style and it also lets you refactor at a later date when your http request becomes a stream.



来源:https://stackoverflow.com/questions/58319625/should-i-always-use-observables-where-a-promise-can-be-used

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