首页 > 解决方案 > 在第一个异步完成之前运行的第二个异步函数

问题描述

我正在尝试为节点/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

标签: node.jspostgresql

解决方案


我只是在想问题可能来自创建表时的postgress命名尝试在创建表后检查数据库中表的名称


推荐阅读