node.js - 在第一个异步完成之前运行的第二个异步函数
问题描述
我正在尝试为节点/postgresSQL 设置编写测试。目前在我创建表然后用用户为表播种的步骤。我有一个名为 createUserTable 的异步函数,然后是第二个名为 seedUserTable 的异步函数,但是当我运行它们时,我收到错误“关系“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
解决方案
我只是在想问题可能来自创建表时的postgress命名尝试在创建表后检查数据库中表的名称
推荐阅读
- javascript - 如何通过反应中兄弟组件上的单击事件将图像加载到另一个组件中
- python - 在第二个轴上选择 Numpy
- java - 我怎样才能做一个慢循环?
- java - FirebaseMessagingService onMessageReceived 方法未在后台调用 DATA 有效负载
- sql - 是/否 查询列的格式
- python-3.x - ExcelLibrary - 机器人框架骑行 - 导入问题
- php - 尝试访问 null 类型值的数组偏移量(flashpub)
- json - 在颤动中显示来自 JSON 的选定值
- ios - 无法将应用上传到 App Store 连接
- python - 如何解决 PyCharm 中的 tensorflow 问题?