回调支持
¥Callback Support
async
/await
是目前使用 Node 编写异步代码的首选方式,但 pg
模块和 pg-pool
模块也支持回调。要使用它们,请将回调函数作为最后一个参数传递给以下方法,它将被调用,并且不会返回 promise:
¥async
/ await
is the preferred way to write async code these days with node, but callbacks are supported in the pg
module and the pg-pool
module. To use them, pass a callback function as the last argument to the following methods & it will be called and a promise will not be returned:
const { Pool, Client } = require('pg')
// pool
const pool = new Pool()
// run a query on an available client
pool.query('SELECT NOW()', (err, res) => {
console.log(err, res)
})
// check out a client to do something more complex like a transaction
pool.connect((err, client, release) => {
client.query('SELECT NOW()', (err, res) => {
release()
console.log(err, res)
pool.end()
})
})
// single client
const client = new Client()
client.connect((err) => {
if (err) throw err
client.query('SELECT NOW()', (err, res) => {
console.log(err, res)
client.end()
})
})
Last updated on April 25, 2025