簡體   English   中英

在 digitalocean 上使用 node-pg 異步/等待不返回任何內容

[英]Async/Await with node-pg on digitalocean not returning anything

嗨,我正在嘗試從 api/data.js 提供的 server/index.js api 端點data.getData()獲取數據,后者又從 db/index.js 獲取其配置和連接 object。 問題是 async/await 沒有返回任何內容,並且在開發控制台網絡中顯示待處理。 我也沒有收到任何錯誤。 代碼如下。 將 node-pg 與 pool.query 一起使用。

//server/index.js
const express = require("express");
const data = require("./api/data")

const PORT = process.env.PORT || 3001;

const app = express();
app.use(express.json())

app.get('/', async (req, res) => {
    // res.status(200).send('Hello World!');

    await data.getData()
    .then(response => {
      res.status(200).send(console.log(response));
    })
    .catch(error => {
        res.status(500).send(error);
      })
    console.log("server running")
})


app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});


//api/data.js
const db = require('../db/index.js');

const getData = async () => {
    const query = {
        // text: 'SELECT COUNT(*) as count FROM "public"."Subregions-USA";',
        text: 'SELECT Now()',
        // values: ['B007RKDGVQ'],
        // rowMode: 'array',
    };
    
    const dbResults = await db.query(query)
    .then((data) => JSON.stringify(data))
    .catch(error => {
        console.log(error)
      })
    console.log("database response test")

    return dbResults
}

// getData()

module.exports = {getData}

設置非常簡單,但我不明白為什么它不起作用。 在此處輸入圖像描述

我正在嘗試連接到數字海洋中的 postgresql 並且所有連接和配置都是正確的。 我使用了類似的相同設置,但使用 electron.js 並且它可以工作。 我能夠輕松檢索數據。

任何幫助表示贊賞。

您應該避免同時使用async/awaitthen/catch 使用其中之一。

  • 服務器/index.js
const express = require("express");
const data = require("./api/data")

const PORT = process.env.PORT || 3001;

const app = express();
app.use(express.json())

app.get('/', async (req, res) => {
  // res.status(200).send('Hello World!');

  try {
    const result = await data.getData();

    res.status(200).send(result);
  } catch (error) {
    res.status(500).send(error);
  }
  console.log("server running")
});

app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});
  • api/data.js
const db = require('../db/index.js');

const getData = async () => {
  const query = {
    // text: 'SELECT COUNT(*) as count FROM "public"."Subregions-USA";',
    text: 'SELECT Now()',
    // values: ['B007RKDGVQ'],
    // rowMode: 'array',
  };

  const dbResults = await db.query(query);
  console.log("database response test", dbResults)

  return JSON.stringify(dbResults)
}

module.exports = {getData}

好的,我發現了問題,它與邏輯本身無關,但更多與我為 PostgreSQL 安裝的 package 有關。

由於某些愚蠢的原因,我沒有安裝npm i pg而不是安裝 npm npm i node-pg

卸載並安裝正確的 package 后,我可以使用 PostgreSQL 響應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM