Reputation: 25
I have a function to get an attribute from a PostgreSQL table using node-postgresql.
const { Client } = require("pg");
const client = new Client();
client.connect();
const query = (text, params) => client.query(text, params);
const inArray = (arr, el) => (arr.indexOf(el) > -1);
const isValidTable = table => {
const options = ["users", "photos", "comments", "likes"];
return inArray(options, table);
};
const isValidColumn = (table, col) => {
if (!isValidTable(table)) return false;
const options = {
users: [
"id",
"username",
"password",
"email",
"name",
"avatar_id",
"created_at"
]
};
return inArray(options[table], col);
};
const getAttribute = async (table, col, id) => {
if (!isValidColumn(table, col)) return;
const q = `
SELECT ${col}
FROM ${table}
WHERE id = $1
LIMIT 1
`;
const params = [id];
const res = await query(q, params);
return res.rows[0][col];
};
// Returns Promise<Pending>
const att = getAttribute("users", "username", 1);
console.log(att);
// Returns the attribute
(async () => {
const att = await getAttribute("users", "username", 1);
console.log(att);
})();
Why when I call this function I still get a promise, even though I have Async/Await? Also, any suggestions on how to improve this code?
Upvotes: 1
Views: 673
Reputation: 59
asfopoo is partially right, but I think it's more accurate to say that when async functions are called from synchronous code you get a promise. If you want to log the value returned from an async function, write asyncFunction().then( (value) => { console.log(value);});
. .then()
will run after your async call completes.
Upvotes: 2
Reputation: 2682
Async functions always return a Promise, even though your getAttribute
code appears to return an attribute value.
Return value
A Promise which will be resolved with the value returned by the async function, or rejected with an exception uncaught within the async function.
Upvotes: 0
Reputation: 1
await returns a promise, .then() gets the value from the promise
(async () => {
await getAttribute("users", "username", 1).then(response => {
console.log(response);
}})();
Upvotes: 0