Return the client instance in the connect() method (#3564)

* Return the client instance in the `connect()` method

* Added one basic test

* Renamed

* Testing the result

* Added equality check

* Simplified docs for connecting

* Added it to the native client as well

* Added this to the callback
This commit is contained in:
Francisco Presencia 2026-01-28 03:27:08 +09:00 committed by GitHub
parent 5b68a115cc
commit 57e93b5daf
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 12 additions and 7 deletions

View File

@ -44,8 +44,7 @@ The simplest possible way to connect, query, and disconnect is with async/await:
```js
import { Client } from 'pg'
const client = new Client()
await client.connect()
const client = await new Client().connect();
const res = await client.query('SELECT $1::text as message', ['Hello world!'])
console.log(res.rows[0].message) // Hello world!
@ -83,5 +82,3 @@ console.log(res.rows[0].message) // Hello world!
```
Our real-world apps are almost always more complicated than that, and I urge you to read on!

View File

@ -213,7 +213,7 @@ class Client extends EventEmitter {
if (error) {
reject(error)
} else {
resolve()
resolve(this)
}
})
})

View File

@ -119,7 +119,7 @@ Client.prototype._connect = function (cb) {
self.emit('connect')
self._pulseQueryQueue(true)
cb()
cb(null, this)
})
})
}
@ -135,7 +135,7 @@ Client.prototype.connect = function (callback) {
if (error) {
reject(error)
} else {
resolve()
resolve(this)
}
})
})

View File

@ -20,6 +20,14 @@ suite.test('valid connection completes promise', () => {
})
})
suite.test('valid connection returns the client in a promise', () => {
const client = new pg.Client()
return client.connect().then((clientInside) => {
assert.equal(client, clientInside)
return client.end().then(() => {})
})
})
suite.test('invalid connection rejects promise', (done) => {
const client = new pg.Client({ host: 'alksdjflaskdfj', port: 1234 })
return client.connect().catch((e) => {