1

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" return undifined and throw "Cannot read property 'then' of undefined"

I don't understand what happens behind the scenes. Anyone can explain it for me ? Thanks

Dai Nguyen
  • 66
  • 6
  • Run either the callback version or the promise version not both – Kunal Mukherjee Oct 17 '20 at 16:55
  • 1
    @KunalMukherjee If I run just callback twice or promise twice everything is ok – Dai Nguyen Oct 17 '20 at 16:58
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Kunal Mukherjee Oct 17 '20 at 17:00
  • I know how to return result from async function but It is not true for method query of object Client @KunalMukherjee – Dai Nguyen Oct 17 '20 at 17:07
  • The `client.query` gets pushed to the event loop for deferred execution when its ready it will execute the body of the callback, but in the meantime it progresses to the client.query.then and finds it undefined, read how the event loop works here - https://stackoverflow.com/questions/21607692/understanding-the-event-loop – Kunal Mukherjee Oct 17 '20 at 17:12
  • Thanks. I found the reason for this problem – Dai Nguyen Oct 17 '20 at 17:19
  • @DaiNguyen Can you [share it with us](https://stackoverflow.com/help/self-answer), please? – Bergi Oct 17 '20 at 21:00

0 Answers0