node-postgres在连接失败时重新连接

时间:2018-05-29 08:59:27

标签: node.js database postgresql promise

这是我db connection项目的nodejs代码,在某些情况下,我的数据库是downnot working),我想尝试reconnecting to db,但是我不知道该怎么做,请帮帮我

const { Client } = require('pg');
const postgis = new Client({
  user: process.env.PGUSER,
  host: process.env.PGHOST,
  database: process.env.PGDATABASE,
  password: process.env.PGPASSWORD,
  port: process.env.PGPORT
});
console.log(`Connecting to PostGIS database ${process.env.PGDATABASE} on: ${process.env.PGHOST}:${process.env.PGPORT}`);

postgis.connect()
.then(() => {
  console.log(`PostGIS connected to: ${process.env.PGDATABASE} on: ${process.env.PGHOST}:${process.env.PGPORT}`)
})
    .catch((e) => {
  // console.error(`PostGIS connection error: ${e}`)
  setTimeout(function () {
    console.log("entering again")
    postgis.connect();
  }, 10000);

});

错误:

(node:10299) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:10299) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

1 个答案:

答案 0 :(得分:1)

你可以在catch块中处理它并重新连接到posgres

curl_easy_setopt