我正在尝试从我的 postgresql 数据库查询数据。我正在使用 pg 并使用 client.query 查询数据。我成功地进行了查询,但是当我离开 client.query 调用的函数时,我丢失了数据。我不确定它是否与等待有关,但我需要它才能正常工作。
var data;
const connectionString = 'postgres://postgres:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a2a35292e3d283f291a292e35283f3e3874392923303c23343d6f2c3d39742f29772d3f292e776874283e29743b373b2035343b2d2974393537" rel="noreferrer noopener nofollow">[email protected]</a>: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 时与 wait 一起使用:
https://node-postgres.com/api/client#client.query
var data;
const connectionString = 'postgres://postgres:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aadac5d9decdd8cfd9ead9dec5d8cfcec884c9d9d3c0ccd3c4cd9fdccdc984dfd987ddcfd9de879884d8ced984cbc7cbd0c5c4cbddd984c9c5c7" rel="noreferrer noopener nofollow">[email protected]</a>: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);
关于javascript - 使用await 在函数调用之外保留数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61744301/