我试图从我的postgresql数据库中查询数据。我使用pg,并使用client.query来查询数据,我成功地进行了查询,但是当我离开client.query调用的函数时,我失去了数据。我成功地进行了查询,但是当我离开client.query调用的函数时,我丢失了数据。我不确定这是否与 await 有关,但我需要 await 来让它工作。
var data;
const connectionString = 'postgres://postgres:[email protected]:5432/clientdb';
const client = new Client({
connectionString: connectionString
});
await client.connect();
await client.query('SELECT * from public.clients', function (err, res) {
if (err) {
console.log("This is the Error")
console.log(err);
return err;
}
client.end();
data = res.rows;
});
console.log("data", data);
res.rows给我提供了我想要的数组,但是当我把它设置为data时,data是未定义的。Console.log("data", data)返回。
data undefined
我怎样才能让这些数据在client.query调用的函数之外持久化?
client.query
如果返回一个Promise的话,只能用 await工作。https:/node-postgres.comapiclient#client.query。
var data;
const connectionString = 'postgres://postgres:[email protected]:5432/clientdb';
const client = new Client({
connectionString: connectionString
});
await client.connect();
let res = await client.query('SELECT * from public.clients');
data = res.rows;
console.log("data", data);