Search code examples
node.jspostgresqlfunctionvue.jsreturn-value

Return a List fetched from postgres


I want to get data from Postgres DB, and to transfer that data to Vue front end, using Node JS

Here I created seperate function for fetching data. This is my function defenition.

    function fetchshop(){
    pool.query('SELECT * FROM shops',(err, shps) =>{
     if (err){
         throw err
     }
     else {
         shopdetails=shps.rows;
         console.log(shopdetails)  // Here the data is printed in console
         return shopdetails;
     }
    
    });
 
    }

I am able to print data rows in the console from the pool.query section, But at the function call section when I try to print the returned data in the console it showng undefined. And this is my function calling code

    events=[];
    shopdetails=[];

    app.get("/home",async (request,response,err)=>{
      events = fetchshop();
      console.log(events)   // This prints 'undefined' in console
      response.send(events);  // I want to send this events.
    })

Solution

  • The reason for this is, your code inside of fetchshop runs asynchronously but you expect a synchronous behaviour. Your query method accepts a callback that is executed asynchronously after data was fetched from Postgres. fetchshop finishes before query succeeded and therefore without returning anything, undefined. You have to promisify your code or use a callback passed as argument of fetchshop.

    function fetchshop(callback) {
        pool.query("SELECT * FROM shops", (err, data) => {
            if(err) {
                return callback(err);
            }
    
            return callback(undefined, data.rows);
        });
    }
    
    app.get("/home", (req, res, next) => {
        fetchshop((err, data) => {
            if(err) {
                return next(err);
            }
    
            res.status(200).send(data);
        });
    });
    

    This way, your fetchshop method calls itself a listener, called callback, after finishing data fetching asynchronously. Your HTTP request listener, app.get("/hello", ...), is notified asynchronously when data is loaded and request can be sent.