0

In my TypeScript app I've reached the point where I have a method that internally does several fromPromise and toPromise operations:

  myMethod(...): Promise<string> {
    return fromPromise(this.someService1.someMethod1(...)).pipe(
      mergeMap(param => fromPromise(this.someMethod2(...))),
      map(param => getSomethingFromParam(param)),
    ).toPromise();
  }

also the someMethod1 and someMethod2 internally use toPromise and fromPromise.

I understand that if I put it like this, it looks quite messy. However the reason is to have a clean API in every service (e.g. I mostly use the result of someMethod1 and someMethod2 as promises so I convert their internal observable to a Promise and expose it like this).

I could of course refactor the whole thing, having my services to expose more methods so I can for example call a method that returns me directly an Observable instead of a Promise.

My question is: do I need such a refactor?

In other words: currently my services' APIs are quite clean, they only expose Promises. But I do have to play with fromPromise and toPromise whenever I want to benefit from rxjs operators. So I would like to keep things the way they currently are, unless these operations are expensive (in terms of performance).

Francesco Borzi
  • 56,083
  • 47
  • 179
  • 252

1 Answers1

1

First, Your tag mentions rxjs6, so fromPromise is no longer part of the Global API. Use from instead: fromPromise does not exist on type Observable

Short answer, no it is not expensive.

You are converting it so you can use the power of operators.

Well, toPromise was once an operator and now has been merged directly to the Observable class.

If we look at the implementation of toPromise:

toPromise(promiseCtor?: PromiseConstructorLike): Promise<T | undefined> {
promiseCtor = getPromiseCtor(promiseCtor);

return new promiseCtor((resolve, reject) => {
  let value: T | undefined;
  this.subscribe((x: T) => value = x, (err: any) => reject(err), () => 
    resolve(value));
  }) as Promise<T | undefined>;
 }
}

We can see that toPromise subscribes to the Observable and get a Promise.

All you are doing is chaining like any other operator so you can innerly subscribe to the observable (like MergeMap would do on 10 different Observables for example). Your implementation is legit.

monogate
  • 1,419
  • 1
  • 11
  • 16