javascript - pg client.query() 不等待 await
问题描述
我不明白为什么客户端请求await
前面pg
的代码在函数内部代码之前运行之后似乎不能作为代码工作client.query()
。
const {Pool, Client} = require('pg')
const connectionString = 'postgressql://user@localhost:5432/database'
const client = new Client({
connectionString:connectionString
})
client.connect()
database_func()
async function database_func() {
await client.query(`SELECT t FROM es ORDER BY t DESC LIMIT 1;`, (err,res) => {
console.log('res')
return;
})
client.end()
console.log('after res')
}
我希望上面能返回这个:
=> res
=> after res
相反,它返回:
=> after res
=> res
解决方案
尝试
const {Pool, Client} = require('pg')
const connectionString = 'postgressql://user@localhost:5432/database'
const client = new Client({
connectionString:connectionString
})
client.connect()
database_func();
function database_func() {
client.query(`SELECT t FROM es ORDER BY t DESC LIMIT 1;`, (err,res) => {
console.log('res')
client.end()
console.log('after res')
return;
})
}
使用承诺:
const {Pool, Client} = require('pg')
const connectionString = 'postgressql://user@localhost:5432/database'
database_func().then(() => console.log('done'))
function async database_func() {
const client = new Client({
connectionString:connectionString
});
client.connect()
await query_func(client, `SELECT t FROM es ORDER BY t DESC LIMIT 1;`);
await query_func(client, `SELECT t FROM es ORDER BY t LIMIT 1;`);
client.end()
}
function query_func(client, query) {
return new Promise((resolve, reject) => {
client.query(query, (err,res) => {
if(err) reject(err);
resolve(res);
}
});
}
推荐阅读
- python - AttributeError:“str”对象没有来自 XML 的嵌套字典的属性“值”
- python - 如何访问嵌套索引?
- mysql - React JS如何互连输入表单
- vb.net - 如何通过一组文本框循环 SQL 命令
- scala - 如何在不阻塞的情况下运行一系列期货并等待完成?
- c++ - 错误:向类构造函数添加参数时没有匹配的函数调用
- android - 文本视图之外的 Android 按钮
- c++ - 如何解决 enqueueWriteBuffer 上的错误 -36?
- object - 如何在 Ocaml 的对象中使用另一个 val 定义一个 val?
- sas - 如何存储和传递我的 SAS 结果值?