When would it be beneficial to change an Observable to a promise
I'm working with Angular 2 and I was wondering if anyone could explain a situation in when it would be beneficial to convert and Observable to a promise?
Ex. Rx.Observable.toPromise()
I know the differences between promises & Observables. Again, I was just curious as to what type of situation the toPromise()
operator would come in handy for.
Thanks :)
The obvious situation is when you are imposed an API, that API only interfaces with promises, some of the inputs for that API you get as observables. If all these conditions are met, then you have to convert your observable to a promise.
How would you get an observable which only represents one value, or where you care only about the last value? Well, same thing. Your observable might be returned by an imposed API, that API only interfaces with observables etc.
So the main reason to use .toPromise
is when you actually don't have a choice and must convert.
A promises fires exactly once. So the first requirement for converting an observable to a promise is that observable emits only once (or you only care about the first emission).
The promise API is more straightforward than observables--basically just then
and catch
, with it being easy to hang additional then
branches from those, whereas with observables you have to subscribe, and then potentially worry about unsubscribing.
You may also have downstream code with expects a promise, so as another answer states, you'll need to convert to a promise to interface with it.
链接地址: http://www.djcxy.com/p/55472.html