node.js - 为什么我的 async/await Postgres 查询返回 undefined?

标签 node.js postgresql async-await jestjs

在下面的 Jest 测试中,我无法理解 undefined 的来源。这是源文件:

// UserAPI.js - file being tested
const { Client } = require('pg')
const dbConfig = require('../db')

const findUserById = ({ userId }) => {
  const client = new Client(dbConfig)
  client.connect()

  return client
    .query('SELECT * FROM users WHERE id = $1', [userId])
    .then(result => {
      if (result.rowCount === 0) {
        return null
      }
      const foundUser = result.rows[0]
      if (foundUser) {
        const { password: storedpassword, ...user } = foundUser
        console.log(user)
        return user
      }
    })
    .then(() => client.end())
}

exports.byId = findUserById

这是测试文件:

// UserAPI.test.js - test file
const api = require('../lib/UserAPI')
const { Client } = require('pg')
const SQL = require('sql-template-strings')
const dbConfig = require('../db')
const { clean_db, asyncForEach } = require('./helpers/dbTools')

jest.setTimeout(1000)

const defaultUsers = [
  {
    password: '12345678',
    username: 'smith@example.com',
    forename: 'John',
    surname: 'Smith',
    department: 'Accounts',
  },
  {
    password: '12345678',
    username: 'jones@example.com',
    forename: 'Bill',
    surname: 'Jones',
    department: 'Packing',
  },
]

async function insertUsers(myUsersArray) {
  const client = new Client(dbConfig)
  client.connect()
  return asyncForEach(myUsersArray, async myUser => {
    let {
      password,
      username,
      forename,
      surname,
      department,
    } = myUser
    return client
      .query(
        SQL`INSERT INTO users (password, username, forename, surname, department)
        VALUES ( ${password}, ${username}, ${forename}, ${surname}, ${department})`,
      )
      .catch(err => console.error(err))
  }).then(() => client.end())
}

beforeAll(async () => {
  await clean_db('users')
  await insertUsers(defaultUsers)
})

afterAll(async () => {
  await clean_db('users')
  await insertUsers(defaultUsers)
})

describe('Querying the API for User data', () => {
  it('returns an individual user by id without password', async () => {
    const response = await api.byId({ userId: 1 })
    console.log('Response is: ', response)
    console.log('Response is of type: ', typeof response)
    console.log('Response properties: ', Object.keys(response))
    expect(response.username).toStrictEqual('smith@example.com')
    expect(response.id).toStrictEqual(1)
  })
)

运行测试时得到的结果:

 FAIL  tests/UserAPI.test.js
  ● Console

    console.log lib/UserAPI.js:43
      { id: 1,
        username: 'smith@example.com',
        created: 2020-01-02T16:29:19.221Z,
        modified: null,
        forename: 'John',
        surname: 'Smith',
        department: 'Accounting'
      }
    console.log tests/UserAPI.test.js:68
      Response is:  undefined
    console.log tests/UserAPI.test.js:69
      Response is of type:  undefined

  ● Querying the API for User data › returns an individual user by id without password

    TypeError: Cannot convert undefined or null to object
        at Function.keys (<anonymous>)

      68 |     console.log('Response is: ', response)
      69 |     console.log('Response is of type: ', typeof response)
    > 70 |     console.log('Response properties: ', Object.keys(response))
         |                                                 ^
      71 |     expect(response.username).toStrictEqual('smith@example.com')
      72 |     expect(response.id).toStrictEqual(1)
      73 |   })

      at Object.it (tests/UserAPI.test.js:70:49)

我无法理解的是用户是如何从API.js文件中得到控制台的,但没有返回到const response = wait api.byId ({ userId: 1 }) 行?鉴于控制台输出按预期顺序排列,这不是异步问题,对吗?

最佳答案

将最后一个 then 更改为 finally。它将始终关闭客户端连接并返回 user,正如前面 then 所预期的那样。

关于node.js - 为什么我的 async/await Postgres 查询返回 undefined?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59566905/

相关文章:

c# - 每个请求的连接

c# - Task.Delay 与 Thread.Sleep 的区别

javascript - 如何从异步调用返回错误

javascript - 在express中正确使用app.set()?

javascript - 在 Node js module.exports 中创建回调

html - 如何从nodejs创建和存储html页面?

postgresql - Citus 是否公开了用于修剪碎片的哈希函数?

node.js - 如何在 Node.js 中安全地运行用户提交的脚本

postgresql - 如何连接到 scala 中的 postgreSQL 数据库?

postgresql - Postgres 无法监听特定 IP 地址