问题
Is it a good practice to convert the observable object to a promise since observable can be used in almost all the occasions instead of promise?
I've started to learn angular recently and come across the below code snippet in a new project(Angular 5) at my workplace. This code snippet is used to load a list of data such as a customer list. This customer list data set is received as a one time action, not as a stream. Therefore it has no technical limitation to use promise. But I would like to know whether there are any drawbacks or limitations.
getViewDataForPage(): Promise<any> {
return this.commonDataService.getViewDataForPage(args_set)
.toPromise()
.catch(error => this._exceptionService.catchBadResponse(error));
}
//in commonDataService.ts
getViewDataForPage(args_set): Observable<any> {
/** logic goes here */
return this.httpConnection.post(viewDataRequest, args);
}
回答1:
It depends on your requirement, technically observables are better than promises because they provide the features of Promise and more. With Observable, it doesn't matter if you want to handle none to multiple events.
Observables
are cancelable ie., using unsubscibe()
you can cancel an observable irrespective of its state.
Promises
on the other hand deal with only 1 async event ie.., either it will resolve or reject if error occurs
A good place for Promise
would be if you have a single even to process for example.
let connect=new Promise((resolve,reject)=>{
if( connection Passed){
resolve("Connected");
} else{
reject("failed");
}
}
回答2:
You can use both. The Observable is used when you are going to receive different values during the time is more like when you are a subscriptor in a some magazine, when ever the mazagazine has new edition you will be notifier and the same happens to all subscriptors and everybody receives the new value or in this case the new magazine.
In the case of the Promise it is Async like an observable but it just happen ones.
Then if the following code will happens ones in this case is ok the promise
getViewDataForPage(): Promise<any> {
return this.commonDataService.getViewDataForPage(args_set)
.toPromise()
.catch(error => this._exceptionService.catchBadResponse(error));
}
//in commonDataService.ts
getViewDataForPage(args_set): Observable<any> {
/** logic goes here */
return this.httpConnection.post(viewDataRequest, args);
}
来源:https://stackoverflow.com/questions/52257515/converting-observable-to-promise