我正在尝试为节点/ postgresSQL安装编写测试。目前,在我创建表并向用户植入表的步骤中。我有一个名为createUserTable的异步函数,然后有一个名为seedUserTable的第二个异步函数,但是当我运行它们时,出现错误“ relation“ public.user”不存在。我对为什么我的第二个异步功能在第一个异步功能完成之前运行感到非常困惑。
这是我的代码
const { Pool } = require('pg');
const { DB_HOST, DB_USERNAME, DB_PASSWORD, DB_PORT, DB_TEST_DATABASE } = require('./config');
const pool = new Pool({
host: DB_HOST,
port: DB_PORT,
user: DB_USERNAME,
password: DB_PASSWORD,
database: DB_TEST_DATABASE,
});
const createUserTable = async () => {
console.log('createUserTable')
try {
const newUserTable = await pool.query(`
CREATE TABLE public.user
(
user_id SERIAL PRIMARY KEY UNIQUE NOT NULL,
username VARCHAR(35) UNIQUE NOT NULL
);
`);
console.log(newUserTable);
} catch (error) {
console.error(error.message);
}
}
const seedUserTable = async () => {
console.log('seedUserTable')
try {
const seedUserTable = await pool.query(`
INSERT INTO public.user(username)
VALUES (
$1
),
(
$2
)
RETURNING *
`,
[
'demo',
'demo2',
]
);
console.log(seedUserTable);
} catch (error) {
console.error(error.message);
}
}
createUserTable();
seedUserTable();
这就是我要进入终端的情况。
$ node index2.js
createUserTable
seedUserTable
relation "public.user" does not exist
Result {
command: 'CREATE',
rowCount: null,
oid: null,
rows: [],
fields: [],
_parsers: undefined,
_types: TypeOverrides {
_types: {
getTypeParser: [Function: getTypeParser],
setTypeParser: [Function: setTypeParser],
arrayParser: [Object],
builtins: [Object]
},
text: {},
binary: {}
},
RowCtor: null,
rowAsArray: false
}
编辑:从这两个函数中删除了异步,并将调用包装在这样的异步函数中。
(async () => {
await createUserTable();
setTimeout(() => {
console.log('5000 ms timeout');
}, 5000);
await seedUserTable();
})();
当前出现此错误:
createUserTable
Promise { <pending> }
seedUserTable
Promise { <pending> }
(node:19684) UnhandledPromiseRejectionWarning: error: relation "public.user" does not exist
5000 ms timeout
答案 0 :(得分:0)
我建议删除您添加的所有异步功能,并在下面进行操作:
(async() => {
await createUserTable();
await seedUserTable();
})();
答案 1 :(得分:0)
我只是在想问题可能来自于创建表时的postgress命名 创建数据库后,尝试检查数据库中表的名称