Are the fromPromise and toPromise functions in Rxjs resource-intensive?

Within my TypeScript application, I have come to a stage where one of my methods performs multiple operations with fromPromise and toPromise:

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

Both someMethod1 and someMethod2 utilize toPromise and fromPromise internally as well.

I acknowledge that the current implementation may seem cluttered, but it is designed to maintain a clean API in each service (for instance, I primarily utilize the promise results from someMethod1 and someMethod2, so I convert their internal observables to promises and expose them accordingly).

Potentially, I could revamp the entire structure by enhancing my services to offer more specific methods. This would enable me to directly call a method that yields an Observable instead of a Promise.

Hence, my query persists: is such a restructuring necessary?

To elaborate further: at present, the APIs of my services appear tidy, solely showcasing Promises. Nonetheless, dealing with fromPromise and toPromise becomes requisite whenever making use of rxjs operators. Unless these maneuvers significantly impact performance, I prefer retaining the existing setup.

Answer №1

Initially, your tag refers to rxjs6, meaning that fromPromise is no longer part of the Global API. Instead, use from: fromPromise does not exist on type Observable

In a nutshell, it is not costly.

The conversion enables you to leverage the capabilities of operators.

Previously, toPromise functioned as an operator but now it has been incorporated directly into the Observable class.

By looking at the inner workings 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>;
 }
}

It can be observed that toPromise subscribes to the Observable and obtains a Promise.

Your approach essentially involves chaining similar to any other operator in order to internally subscribe to the observable (similar to what MergeMap would accomplish with multiple Observables). Your method is valid.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add integer to an array of strings

Currently, I am utilizing an autocomplete feature and aiming to save the IDs of the selected users. My goal is to store these IDs in a string array, ensuring that all values are unique with no duplicates. I have attempted to push and convert the values u ...

A guide on crafting a type definition for the action parameter in the React useReducer hook with Typescript

In this scenario, let's consider the definition of userReducer as follows: function userReducer(state: string, action: UserAction): string { switch (action.type) { case "LOGIN": return action.username; case "LOGOUT": return ""; ...

Eliminating null values from a multidimensional array

Is there a way to remove the array elements cctype, cctypologycode, and amount if they are empty? What would be the most efficient approach? { "ccInput": [ { "designSummaryId": 6, "CCType": "A", "CCTypologyCode": "A", "Amount ...

Tips for configuring Visual Studio Code to utilize path mappings for handling automatic imports

In order to streamline my project and avoid messy paths, I am implementing absolute paths that will allow for consistent imports regardless of the file's location in the project tree. For this purpose, I made adjustments to the tsconfig.json: "paths ...

Discover the process of changing a prop with a button click in NextJS

In my NextJs project, I have a video player component that displays videos using a {videoLink} prop: <ReactPlayer playing={true} controls={true} muted={true} loop={true} width="100" height="100" url={videoLinkDeep} poster="ima ...

Error: Interface declaration for _.split is missing in the Lodash.d.ts file

For my current typescript project that heavily relies on Lodash with lodash.d.ts, I've encountered an issue with the _.split function not being implemented yet. It's listed under the 'Later' section in the .ts file. I need to find a wo ...

ExpressJs Request Params Override Error

I am currently utilizing express version 4.19.2 (the latest available at the time of writing) This is how I have declared the generic type Request interface ParamsDictionary { [key: string]: string; } interface Request< P = core.ParamsDictionary, ...

Incompatibility Issues with TypeScript Function Overloading

In the process of setting up an NgRx store, I came across a pattern that I found myself using frequently: concatMap(action => of(action).pipe( withLatestFrom(this.store.pipe(select(fromBooks.getCollectionBookIds))) )), (found at the bottom ...

How do I specify TypeScript types for function parameters?

I've created a function and used TypeScript to define parameter types: const handleLogin = async ( e: React.FormEvent<EventTarget>, navigate: NavigateFunction, link: string, data: LoginDataType, setError: React.Dispatch<Re ...

The address :::3000 is already in use by NestJS

While attempting to deploy my NestJs server on a C-Panel hosting, I have encountered an issue. Despite properly installing all node_modules and ensuring every project file is in place, the server fails to start and continuously displays the following error ...

Text in Angular vanishes upon reopening

I have a code snippet where I am trying to allow the user to edit and save a paragraph displayed on a side panel of the main page. Although the code works fine, allowing users to update the text and see it reflected in the network upon saving, there seems ...

Angular 8 experiencing unexpected collision issues

Currently, I am utilizing Angular 8 with "typescript": "~3.5.3". My objective is to handle the undefined collision in my code. const { testLocation } = this.ngr.getState(); this.step2 = testLocation && testLocation.step2 ? testLocat ...

"Exploring the possibilities of integrating Typescript into Material-UI themes: A step-by

I'm experiencing some issues with Typescript pointing out missing properties in the palette section. Although adding //@ts-ignore resolves the problem temporarily, I would prefer to find a cleaner solution. As a newbie to Typescript, here is my attemp ...

Images with spaces in their names are failing to load in React Native

I am currently trying to utilize an image within my react native application. At this point, my code is very minimal. The following code snippet is all I have for now: import React from 'react'; import { ScrollView, View, Text } from 'reac ...

What is the best way to display multiple HTML files using React?

Looking to develop a web application using React that consists of multiple HTML pages. For instance, login.html and index.html have been created and linked to URIs through the backend - resulting in localhost:8080/login and localhost:8080/index. However, R ...

What is the best approach to implementing a blur function for a specific input within a parent component?

I have created a custom input field as a separate component. I want to include multiple input fields in the parent component using directives: <app-input ...></app-input> My goal is to pass the blur event/function to the parent component speci ...

The 'Key' identifier is not valid for indexing the 'Object' data type

Currently attempting to incorporate functional pluck with a specific sound type, but encountering an issue: function extract<Object extends {}, Key = keyof Object>(key: Key): (o: Object) => Object[Key] { return object => object[key]; } Erro ...

The utilization of conditional expression necessitates the inclusion of all three expressions at the conclusion

<div *ngFor="let f of layout?.photoframes; let i = index" [attr.data-index]="i"> <input type="number" [(ngModel)]="f.x" [style.border-color]="(selectedObject===f) ? 'red'" /> </div> An error is triggered by the conditional ...

Join our mailing list for exclusive updates on Angular 6

ingredients : Array additionalIngredients : Array In my code, I have two different methods for subscribing: this.ingredients.valueChanges.subscribe(val=> { console.log(val); } this.additionalIngredients.valueChanges.subscribe(val2=> { console.lo ...

Enroll in various Observers simultaneously using a loop in Angular

Currently, I am facing an issue in my code. The scenario is as follows: I need to iterate through an array of objects (orders) and perform some processing on each order. After that, I have to make multiple API calls for each product within the order' ...