I am looking to create a method within my class that connects to a MySQL database. I have already written my SQL code and now I want to move away from using callbacks and start implementing promises, as it is more modern.
Below is my function with callbacks (old school):
public does_player_exist(username: string, callback: any) {
this.mysql.connect();
this.mysql.query('USE devdb');
this.mysql.query('SELECT p_name FROM players WHERE p_name = "'+username+'"', (err: Error, result: any[]) {
if (result.length === 1) {
callback(true)
} else {
callback(false);
}
});
}
Next is the method where I attempted to use a promise, but unfortunately failed:
public does_player_exist(username: string): Promise<boolean> {
this.mysql.connect();
this.mysql.query('USE devdb');
return this.mysql.query('SELECT p_name FROM players WHERE p_name = "'+username+'").toPromise().then((result) => {
return result.length === 1;
})
}
When I invoke this method:
service.does_player_exist('test').then((result) => { console.log(result) })
I am hopeful that someone can assist me with this transition, as I am eager to embrace more modern practices and move away from the old school ways xD
Thank you in advance.