У меня есть функция для получения атрибута из таблицы PostgreSQL с использованием 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);
})();
Почему, когда я вызываю эту функцию, я все равно получаю обещание, даже если у меня есть Async /Ждите? Также есть предложения по улучшению этого кода?