我正在学习Typescript,并且为了练习,我试图开发一个简单的类来执行SQL语句。但是我不知道如何将具有值的类属性设置为回调函数,因为我无法从类构造函数中读取它。这是我的恢复和注释代码:
class Sql {
private connection: any
public result: String
constructor() {
// connection initialization
// ...
}
public select = function(table: String) {
let queryString = `SELECT * FROM ${table}`
this.exec(queryString)
}
private exec = function(query: String) {
let result
this.connection.query(query, (err, res) => {
if (err) {
result = JSON.stringify({
result: null,
error: err
})
} else {
result = JSON.stringify({
result: res,
error: null
})
}
console.log(result) // works ok
this.result = result
})
}
}
let sql = new Sql()
sql.select('posts')
console.log(sql.result) // this line returns undefined