2

I am trying to retrieve data from a PSQL table. And this is my code for that:

async function requestData() {
   var selectQuery = `SELECT "fName", "lName", "phoneNumber", "eMail" FROM public."User"`;
   const {rows} = await client.query(selectQuery);
   client.end;
   return rows;
}

This function is returning: an array inside the Promise keyword. {[]}

I want to destructure the array inside to present the data and I cannot figure out any possible way of doing it. I tried using foreach loop and other ways but it is not working.

When this function runs in its own file, it gives normal output of an array of objects.

async function requestData() {
   var selectQuery = `SELECT "fName", "lName", "phoneNumber", "eMail" FROM public."User"`;
   const {rows} = await client.query(selectQuery);
   client.end;
   console.log(rows);
   return rows;
} 

It is giving normal output in the file, but when I am exporting this output, it is wrapping the output in the promise keyword. I tried going through the documentation but I didn't find any way to destructure this.

This is the code in the file that I have imported:

const adminData = require("./data/adminDataObjects");
console.log(adminData.users.table);

And this is the code in the adminDataObjects file where I have defined this function:

users: {
    body: ``,
    table: requestData(),
    script: `<script>document.querySelector('.users').classList.add('active')</script>`,
  },

I am new to node js and I have already tried to search for the solution in different blog posts, stackoverflow answers and MDN documentation. I even read blog posts about asynchronous javascript and completed a tutorial on promises.

1 Answers1

0

As already mentioned in one of the comment by Andy that the return type of an asynchronous function is a promise, it was the problem here.

I asked one of my friend to resolve the promise and the "Promise" keyword that was showing up went away. Apparently I was making a syntax error while resolving the promise.

This is the code with the problem that is returning return value as an array within an object of the promise keyword.

const adminData = require("./data/adminDataObjects");
console.log(adminData.users.table);

This is how I resolved this error:

    const adminData = require("./data/adminDataObjects");
    app.get("/admin/:path", async (req, res) => {
      const requestKeyword = req.params.path;
      if (requestKeyword === "dashboard") {
        res.render("admin-panel", { data: adminData.dashboard });
      } else if (requestKeyword === "users") {
        var finalValue
        await adminData.users.table.then((value)=>{
           finalValue=value;
        })
        console.log(finalValue);
      } else{
        res.render("admin-panel", { data: adminData.orders });
      }
    });
  • 1
    No, don't use `.then((value)=>{ finalValue=value; })`. Just write `const finalValue = await adminData.users.table;` – Bergi Oct 08 '22 at 16:21