【问题标题】:Return a List fetched from postgres返回从 postgres 获取的列表
【发布时间】:2022-01-25 13:06:54
【问题描述】:

我想从 Postgres 数据库中获取数据,并使用 Node JS

将该数据传输到 Vue 前端

在这里,我创建了单独的函数来获取数据。这是我的函数定义。

    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;
     }
    
    });
 
    }

我可以在控制台中从pool.query 部分打印数据行,但是在函数调用部分,当我尝试在控制台中打印返回的数据时,它显示了undefined。这是我的函数调用代码

    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.
    })

【问题讨论】:

    标签: node.js postgresql function vue.js return-value


    【解决方案1】:

    原因是,fetchshop 中的代码异步运行,但您期望同步行为。您的 query 方法接受一个回调,该回调在从 Postgres 获取数据后异步执行。 fetchshop 在查询成功之前完成,因此不返回任何内容,undefined。您必须承诺您的代码或使用作为 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);
        });
    });
    

    这样,您的fetchshop 方法在完成异步数据获取后,会调用自己的侦听器,称为callback。您的 HTTP 请求侦听器 app.get("/hello", ...) 在加载数据并可以发送请求时收到异步通知。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-20
      • 2015-12-13
      • 1970-01-01
      • 2015-11-21
      • 2013-01-15
      • 1970-01-01
      • 2015-04-03
      相关资源
      最近更新 更多