Converting "promises" to "string" using static methods in TypeScript

I am struggling with incorporating "promises" into my TypeScript code. I am currently developing an e2e testing framework using Protractor and TypeScript, and I need to make database queries to retrieve data for filling forms or performing validations.

To address this issue, I created a new class called "UserService" where I plan to implement static methods to fetch the required data. I have also integrated the typeOrm library to handle database operations.

However, I am facing difficulty in converting the results of promises into strings. Can anyone guide me on how to achieve this?

Here is a snippet of the code:

import "reflect-metadata";
import { User } from "././entities/user";
import { ConnectionOptions, Connection, Driver, createConnection } from "typeorm";

const connectionOptions: ConnectionOptions = {
    driver: {
        type: "mysql",
        host: "localhost",
        port: 3306,
        username: "root",
        password: "admin123",
        database: "user"
    },
    entities: [User],
    autoSchemaSync: false
};

export class UserService {

    static getUserName(userId:number): string {

        let us = createConnection(connectionOptions).then(connection => { 
            return connection.getRepository(User).findOne({Id: userId})
        }).then(user => user.name);

        return us;  //it return an Promise<string>.
    }
}

In the context of "step" classes, the above class will be utilized as follows:

let name: string = UserService.getUserName(1);
txtUsername.Sendkeys(name);

Answer №1

Opt for await/async:

const user = await UserService.getUser(1);
txtUsername.Sendkeys(user.name);

Make sure to encapsulate this within an async function, and consider adding a try/catch block since it won't execute synchronously but is the simplest way to handle it.

Don't underestimate the power of promises... they are truly amazing.

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

Generating a fresh instance of a class that mirrors an already existing instance, all without relying on eval()

I have an object named uniqueObject of an unspecified class and I am in need of creating a duplicate object from the same class. Here's my current approach: I extract the class name using uniqueObject.constructor.name. Then, I generate a new object o ...

Having trouble retrieving a controller property in my Angular 2 view

I'm dealing with an interface right now export interface IInterview { id: number; title: string; body: string; } When I use console.log(interview) in my controller, it displays: Object {title: "I SEE SOMETHING", id: 2, body: "THIS IS SO ...

Accessing the menu

There are two main headings in my menu: Administration and Market https://i.sstatic.net/JbePq.png When I click on the Administration heading, submenus for Portfolio and Corporate Action are displayed https://i.sstatic.net/oyabv.png The issue I am facin ...

The function Event.target.value is coming back as null

I've been working on creating a timer window, and I've set up a separate component for it. However, I'm facing an issue with passing the time from the main component to the child component. The problem lies in the fact that the state of the ...

Rendering a component in React based on multiple conditions

Checking sessionStorage and another state variable before rendering a component is essential for my application. I want to avoid showing the same message multiple times within the same session. This is how I have implemented it: const addSession = (noteId: ...

What is the best approach to managing a 204 status in Typescript in conjunction with the Fetch API

Struggling to handle a 204 status response in my post request using fetch and typescript. I've attempted to return a promise with a null value, but it's not working as expected. postRequest = async <T>(url: string, body: any): Promise ...

Unable to locate the 'socket.io' module in a TypeScript project on Visual Studio using node.js

Currently working on a node.js project within Visual Studio. Everything was running smoothly until I attempted to import 'socket.io' and encountered the error message – Cannot find module 'socket.io'. Despite having it installed in th ...

How can I retrieve the value of an array using ngForm in Angular 2?

One concrete example is a component I created that looks like this. @Component({ selector: 'home', template: ` <form (ngSubmit)="onSubmit(f)" #f="ngForm"> <input type="text" ngControl="people"> ...

Typescript: Implementing a generic function with the flexibility of an optional parameter

Having some difficulty writing a generic function with an optional parameter type Action<TParameters = undefined> = (parameters: TParameters) => void const A: Action = () => console.log('Hi :)') // This works as expected const B: ...

The guide to integrating the npm package 'mysql-import' into a node.js project with TypeScript

I'm currently facing an issue while trying to import a dump to a database using node.js and the npm module 'mysql-import'. Initially, I wrote the code in JavaScript and it worked flawlessly. However, when I attempted to modify it for TypeScr ...

The aspect ratio of Threejs sprites is appearing distorted

I'm facing an issue with rendering two objects in an Orthographic camera using Three.js. The objects are not rendering correctly and I'm unsure of the reason behind it. The expected look of the two images is as follows: https://i.sstatic.net/hQ ...

Node.js does not allow the extension of the Promise object due to the absence of a base constructor with the required number of type

I'm trying to enhance the Promise object using this code snippet: class MyPromise extends Promise { constructor(executor) { super((resolve, reject) => { return executor(resolve, reject); }); } } But I keep encou ...

Why can't a TypeScript string be assigned to a union type of string literals?

I have defined a type called Direction, which is a union of the strings 'LEFT' and 'RIGHT'. However, TypeScript (tsc) is giving me an error when I try to assign a 'LEFT' string to it. Here's the code snippet: type Directi ...

Is there a way to apply Validators.required just once for all required form fields in a Reactive Form?

Latest version of Angular is 4.4.3. In Reactive Form, you can use Validators.required for each form field as shown below: this.loginForm = this.fb.group({ firstName: ['', [Validators.required, Validators.maxLength(55)]], ...

Automate the process of replacing imports in Jest automatically

Currently, I am in the process of setting up a testbench for a more intricate application. One challenge we are facing is that our app needs to call backend code which must be mocked to ensure the testbench runs efficiently. To address this issue, we utili ...

Utilizing vue-property-decorator: Customizing the attributes of @Emit

After seeing the @Emit feature, I checked out the example on GitHub. import { Vue, Component, Emit } from 'vue-property-decorator' @Component export default class YourComponent extends Vue { count = 0 @Emit() addToCount(n ...

Unfamiliar String Conversion to JSON in Java

Need assistance with parsing a JSON-formatted string obtained from a URL. The field and size of the data may vary, making it difficult to iterate over the structure of the JSON object. Here is an example of the string: {"_index":"my_index","_type":"my_t ...

I must be patient until the component is visible on the screen, says Protractor

Currently facing an issue where I have to wait for a component to appear on the screen, but sometimes it takes too long to load. Is there a way to wait until a specific field or variable becomes true? element(by.id('nextStage-button')).isPresent ...

Adding an HTML input element to a span tag does not seem to function as intended in Angular 2

Hey, I'm working on a form that requires users to replace text in a sentence. For example, 'Today is ', where the user will enter the current day. However, I'm facing difficulty injecting inputs using 'innerHTML' alone. Here&a ...

Filtering JSON array data in Typescript can help streamline and optimize data

Recently diving into Angular, I am facing a challenge with filtering data from a JSON array. My goal is to display names of items whose id is less than 100. The code snippet below, however, is not producing the desired result. list : any; getOptionList(){ ...