Reputation:
For some reason I am getting undefined before the actual data using the following code
async findOne(query: string, parameters: string): Promise<T> {
const stmt: sqlite3.Statement = await this.db.prepare(query)
const info: T = stmt.get(parameters)
this.db.close()
return info
}
const user = await respository.findOne('SELECT * FROM users WHERE id = ?', targetUser.id)
console.log(user)
The console log outputs undefined and a object after that, what is the reason for this?
Upvotes: 1
Views: 94
Reputation: 930
Probably you will also need await
here:
const info: T = await stmt.get(parameters);
From the documentation here it seems that .get
is a classic callback function, so you will probably need to wrap it inside a Promise before using it with await.
Probably the same is true about this.db.prepare(query)
? Checkout util.promisify
from the standard node library if you don't want to do the promise wrapping yourself.
Also, you can't call an async function in open code. Try this:
(async () => {
const user = await respository.findOne('SELECT * FROM users WHERE id = ?', targetUser.id)
})();
Hope this helps!
Upvotes: 1