Home > OS >  I'm getting an error when I search the database and I don't know how to solve it
I'm getting an error when I search the database and I don't know how to solve it

Time:10-18

I'm making a request to my database, I set the functions as asynchronous and to wait, but it still returns me undefined or Promise { pending } how do I just return it when I have the result?

export const getGerente = async (req, res) => {
    var query = "SELECT * FROM inventory;"
    const r = await select(query)
    console.log(r)
    return res.json({message:"teste"})
}
export async function select(query)  {
   var teste = await client.connect(() =>{
        client
            .query(query)
            .then((resultado) => {
                console.log('sucess!!');
                return resultado.rows
                /*
                const rows=resultado.rows
                rows.map(x =>{
                    console.log(x.name)
                })*/
            })
            .catch((erro) => {
                console.log("erro: "   erro.message);
            })
            .then((teste) => {
                console.log('Finished execution, exiting now');
                process.exit();
            });
    })
}

result: Promise { pending } I'm calling her for a request

CodePudding user response:

Your select function is not awaiting the client.connect properly.

Try this for select function -

export async function select(query)  {
   const promisifiedRows = new Promise((resolve, reject) => {
      client.connect((err) => {
         if (err) {
            reject(err);   // err in connecting
         } else {
            console.log('Connected!');
            client.query(query, (err, rows) => {
               if (err) {
                  reject(err);   // err while exceuting the query
               } else {
                  resolve(rows);
               }
            });
         }
      });
   });

   const rows = await promisifiedRows();
   return rows;
}
  • Related