Skip to content Skip to sidebar Skip to footer

Converting Observable To Promise

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 recen

Solution 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=newPromise((resolve,reject)=>{

if( connection Passed){
   resolve("Connected");
 } else{
   reject("failed");
 }
}

Solution 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> {
    returnthis.commonDataService.getViewDataForPage(args_set)
      .toPromise()
      .catch(error => this._exceptionService.catchBadResponse(error));
  }


  //in commonDataService.ts
  getViewDataForPage(args_set): Observable<any> {
    /** logic goes here */returnthis.httpConnection.post(viewDataRequest, args);
  }

Post a Comment for "Converting Observable To Promise"