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);