I'm new to async functions and I'm struggling getting it do work with db queries... Here's what I have:
fetch: async (id) => {
if (id!=='something') {
return await db.getConnection().query("SELECT user FROM `table` WHERE id='" + id + "'", function (err, result) {
if (err) { throw err }
else {
console.log(result[0].user);
return result[0].user;
}
});
}
throw new Error('Failed fetching installation');
}
This results in getting an error: Cannot read property 'user' of undefined , but after this error, the console.log comes in indicating result[0] is actually defined.
So my guess is that it's not waiting for the result or something like that (even though it's not hitting the throw new Error).
Anyway, I'm sure this is just me not getting this right... as said, I'm only just getting started with these kinds of async behaviors.
As mentioned above you are mixing promises and callbacks. I am unsure if my example below is possible with your database library, but I think if it is, its a much cleaner approach.
const fetch = async (id) => {
if (id !== 'something') {
try {
const query = await db
.getConnection()
.query("SELECT user FROM `table` WHERE id='" + id + "'")
return query[0].user
} catch (error) {
console.log(error)
throw new Error(`Execution of query failed with error: ${error}`)
}
}
throw new Error('Failed fetching installation')
}
const user = fetch('your-id') // (prefix fetch with await if not at top level)