Why is this still returning a promise?

etts :

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?

Travis Jones :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29877&siteId=1