Dai Nguyen
Dai Nguyen

Reputation: 64

Why method async function query of node-postgres return undefined

I learning how to connecting nodejs and postgresql and I follow examples on https://node-postgres.com/features/queries

I have trouble with this example

import { Client } from "pg"

const client = new Client()
client.connect()
const query = {
    name: 'fetch-user',
    text: 'SELECT * FROM users WHERE id = $1',
    values: [1],
}

client.query(query, (err, res) => {
    if (err) {
        console.log(err.stack)
    } else {
        console.log(res.rows[0])
    }
})

client
    .query(query)
    .then(res => console.log(res.rows[0]))
    .catch(e => console.error(e.stack))

If I run the promise style first everything will work fine. If I run callback style first the method "query" returns "undefined" and throws an error:

Cannot read property 'then' of undefined

I don't understand what happens behind the scenes.

Can anyone explain it for me?

Thanks

Upvotes: 0

Views: 237

Answers (0)

Related Questions