ETT:
私は、ノードの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);
})();
私はこの関数を呼び出すときに、なぜ私はまだ、私は非同期/待たを持っているにもかかわらず、約束を得ますか?また、このコードを改善する方法上の任意の提案ですか?
トラヴィス・ジョーンズ:
asfopooは部分的に正しいですが、私はそれが非同期関数は、同期コードから呼び出されたとき、あなたが約束を得ると言うことは、より正確だと思います。あなたは、書き込みを非同期関数から返された値を記録したい場合asyncFunction().then( (value) => { console.log(value);});
。.then()
あなたの非同期呼び出しが完了した後に実行されます。