Вот примерный код, который поможет вам начать создавать слой БД для задач.Использование async / await, которое всегда использует Promises, делает ваш код более процедурным и облегчает анализ.Это то, что вы хотели?
interface ITask {
id: number;
a: string;
b: number;
}
class TasksManager {
private _dbConnection; // a DB Connection object
private _connected: boolean;
private _dbUsername: string;
private _dbPasssword: string;
constructor() {
// do init stuff here for the DB
}
private async connect() {
// actual code that connects to the DB
}
private async diconnect() {
// actual code that disconnects from the DB
}
private async doQuery(querystring: string) {
// use the dbconnection object to do the query and get the results
let a: Array<string> = [];
return a; // this actually returns a Promise as the function is 'async'
}
/*********************
* PUBLIC API
*********************/
set username(v: string) {
this._dbUsername = v;
}
set password(v: string) {
this._dbPasssword = v;
}
public async deleteTask(t: ITask) {
if (!this._connected) {
await this.connect();
}
// create the querystring and execute the query
let qstring = "DELETE * FROM TASKS WHERE ID = " + t.id;
let result = await this.doQuery(qstring);
// do stuff with the results
if (result[0] == "OK") {
return true; // this actually returns a Promise as the function is 'async'
} else {
return false; // this actually returns a Promise as the function is 'async'
}
}
public async updateTask(t: ITask) {
if (!this._connected) {
await this.connect();
}
// code to update task.....
let result = await this.doQuery("UPDATE TASKS ...."); // this blocks until the query returns
if (result[0] == "OK") {
return true; // this actually returns a Promise as the function is 'async'
} else {
return false; // this actually returns a Promise as the function is 'async'
}
}
public async createTask(a: string, b: number) {
if (!this._connected) {
await this.connect();
}
// code to create querystring and do the query to create the task.....
let result = await this.doQuery("INSERT INTO ...."); // this blocks until the query returns
if (result[0] == "OK") {
return true; // this actually returns a Promise as the function is 'async'
} else {
return false; // this actually returns a Promise as the function is 'async'
}
}
}
// create the manager
let taskManager = new TasksManager();
// create new task
taskManager.createTask("one", 2).then((result) => {
if (result == true) {
console.log("task created!!");
}
})
.catch((err) => {
throw `Failed to create task. reason: ${err}`;
});