【问题标题】:Every second time I run the config file it doesn't work每次我运行配置文件时它都不起作用
【发布时间】:2021-05-27 06:08:14
【问题描述】:

我正在使用带有 PSQL 的 node.js,以及 express 和 node-postgres。我有一个名为 config.js 的文件。目的是让它删除数据库,然后在每次运行时将其与表一起重新创建。这会每隔一秒运行一次,在另一半时间返回错误,而不是重新创建数据库。

(node:11300) UnhandledPromiseRejectionWarning: error: database "abc" does not exist

有人知道怎么回事吗?请告诉我是否需要包含完整的错误消息,我没有,因为它看起来不是很有用。

代码:

const { Pool, Client } = require('pg')

let dbName = "abc"

let tables = [{
    name: "users",
    content: "id SERIAL, username VARCHAR, email VARCHAR, passcode VARCHAR"
}]

let pool = new Pool({
    user: 'postgres',
    host: 'localhost',
    database: 'postgres',
    password: 'postgres',
    port: 5432
})

deleteDb()
createDbAndTables()

function deleteDb() {
    pool.query("DROP DATABASE IF EXISTS abc", (err, res) => {

        if (err) {

            console.log(err)
        } else {

            console.log("deleted db " + dbName)
        }
    })
}

function createDbAndTables() {
    pool.query("CREATE DATABASE abc", (err, res) => {

        console.log("created db " + dbName)

        const client = new Client({
            host: 'localhost',
            port: 5432,
            user: 'postgres',
            password: 'postgres',
            database: dbName,
        })

        client.connect()

        for (let i = 0; i < tables.length; i++) {

            let table = tables[i]

            client.query("CREATE TABLE " + table.name + "(" + table.content + ")", (err, res) => {
                if (err) {

                    console.log(err)
                } else {

                    console.log("created table " + table.name)
                }
                if (i == tables.length) {

                    client.end()
                }
            })
        }
        pool.end()
    })
}

如果我做错了什么或可以进行优化,我也很想听听。 提前感谢您的帮助!

【问题讨论】:

  • 当数据库不存在时,看起来像DROP DATABASE IF EXISTS abc 错误?
  • 我不确定是不是这样,因为数据库在那里,我运行文件,它返回错误。
  • 哦,我现在明白了。 deleteDbcreateDbAndTables 两个函数都运行异步代码,但您没有按顺序运行它们。你在这里有一个比赛条件。您必须等待它们以确保它们按顺序运行

标签: node.js postgresql node-postgres


【解决方案1】:

这是确保deleteDbcreateDbAndTables 两个函数按顺序运行的非常快速而肮脏的方法:

const { Pool, Client } = require('pg');

let dbName = 'abc';

let tables = [
  {
    name: 'users',
    content: 'id SERIAL, username VARCHAR, email VARCHAR, passcode VARCHAR',
  },
];

let pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'postgres',
  password: 'postgres',
  port: 5432,
});

deleteDb().then(() => {
  createDbAndTables();
});

function deleteDb() {
  return new Promise((resolve, reject) => {
    pool.query('DROP DATABASE IF EXISTS abc', (err, res) => {
      if (err) {
        reject(err);
      } else {
        resolve('deleted db ' + dbName);
      }
    });
  });
}

function createDbAndTables() {
  pool.query('CREATE DATABASE abc', (err, res) => {
    console.log('created db ' + dbName);

    const client = new Client({
      host: 'localhost',
      port: 5432,
      user: 'postgres',
      password: 'postgres',
      database: dbName,
    });

    client.connect();

    for (let i = 0; i < tables.length; i++) {
      let table = tables[i];
      client.query(
        'CREATE TABLE ' + table.name + '(' + table.content + ')',
        (err, res) => {
          if (err) {
            console.log(err);
          } else {
            console.log('created table ' + table.name);
          }
          if (i == tables.length) {
            client.end();
          }
        }
      );
    }
    pool.end();
  });
}

请注意,我只对其中一个做出了承诺,但如果您想在之后运行,您可能必须同时执行这两个。 我也没有使用async / await,因为我认为这不是在函数中运行,并且为了简单起见,您没有运行最新的节点。

【讨论】:

  • 谢谢!现在每次都有效。很好的答案。
猜你喜欢
  • 1970-01-01
  • 2023-01-23
  • 2023-01-08
  • 1970-01-01
  • 2020-12-15
  • 1970-01-01
  • 1970-01-01
  • 2011-01-20
  • 2018-04-21
相关资源
最近更新 更多