【问题标题】:Why am I getting undefined returned from my async/await Postgres query?为什么我的 async/await Postgres 查询返回未定义?
【发布时间】:2020-04-21 07:53:43
【问题描述】:

在接下来的开玩笑测试中,我无法理解 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)

我不明白的是,user 是如何从 API.js 文件中排除的,但没有返回到 const response = await api.byId({ userId: 1 }) 行?鉴于控制台输出符合预期,这不是异步问题,对吧?

【问题讨论】:

  • 我不完全确定,但可能是因为您的最后一个.then() 正在返回client.end()(其中returns nothing)?

标签: node.js postgresql async-await jestjs


【解决方案1】:

将最后一个then 链接到finally。它将始终关闭客户端连接并按照之前的then 的预期返回user

【讨论】:

  • 这似乎成功了!我现在要运行整个套件,看看是否还有其他问题。谢谢(并回答接受等待;-)! )
  • 太棒了!乐于助人!
猜你喜欢
  • 2021-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
  • 2017-06-09
  • 1970-01-01
相关资源
最近更新 更多