I'm extracting some data from the database, to use it in my nodejs app. I'm using node-postgres to connect to the db ( https://node-postgres.com/ ).
I went through the guidance multiple times and tried querying it in different ways (callback, promise, using pool and client), but always get errors.
const { Pool } = require('pg');
const pool = new Pool({
user: 'user',
host: 'host',
database: 'db',
password: 'pass',
port: port,
});
pool.query('SELECT * from table').then(res=> {
var projects = res.rows;
console.log(projects);
return projects;
});
//... few other operations on projects data to follow before exports
exports.raw = projects;
I can see the data in the console output, so the connection is working, but when I try to run the code I get
ReferenceError: projects is not defined.
Grateful for any help with this.
You can simply achieve by async/await
code format
users.js
const users = {};
const { Pool } = require('pg');
const pool = new Pool({
user: 'user',
host: 'host',
database: 'db',
password: 'pass',
port: process.env.port,
});
users.getUsers = async () => {
try {
const result = await pool.query('SELECT * FROM users');
console.log(result);
return result;
} catch (err) {
console.error(err);
throw err;
}
};
module.exports = users;
friends.js
const friends = {};
const users = require('./users');
friends.getSampleData = async () => {
try {
const result = await users.getUsers();
console.log(result);
return result;
} catch (err) {
console.error(err);
throw err;
}
};
module.exports = friends;
Note
async/await
only works on a function which returns aPromise
.
Just like Jeremy answered, create a getter method in order to fetch data, don't try to store it before you need it.
const fetchData = async() => {
const res = await pool.query('SELECT * from table')
return res.rows;
}
const myDesiredData = fetchData()
Try the async/await
syntax :
let projects;
(async () => {
const res = await pool.query('SELECT * from table');
projects = res.rows;
})();
exports.raw = projects;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.