我具有使用node-postgresql从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 / Await,我仍然可以实现承诺?另外,关于如何改进此代码的任何建议?
await返回一个promise,.then()从promise中获取值
(async () => {
await getAttribute("users", "username", 1).then(response => {
console.log(response);
}})();