我具有使用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,当我调用此函数时,我仍然得到一个诺言?还有,关于如何改进此代码的任何建议?
答案 0 :(得分:2)
asfopoo在某种程度上是正确的,但我认为说从同步代码中调用异步函数可以得到一个诺言更准确。如果要记录从异步函数返回的值,请写入asyncFunction().then( (value) => { console.log(value);});
。 .then()
将在您的异步调用完成后运行。
答案 1 :(得分:0)
await返回一个诺言,.then()从诺言中获取值
(async () => {
await getAttribute("users", "username", 1).then(response => {
console.log(response);
}})();
答案 2 :(得分:0)
Async functions always return a Promise,即使您的getAttribute
代码似乎返回属性值。
返回值
一个Promise,它将由async函数返回的值来解决,或者被async函数中未捕获的异常拒绝。