file ConnectToDB
var pg = require("pg");
var dataWithDB = require('./DataBase/ConnectToDb');
var pool = new pg.Pool({
host: "localhost",
port: "5432",
user: "postgres",
password: "111111",
database: "hrs"
});
pool.connect(function (err,client,done) {
if(err)console.log("connect " + err.toString());
else
client.query('SELECT id, "idName", "idContact", "idExperience",
"idSkill", "dateAdded", "dateColloquy"' +
'FROM public."applicant ";',function (err,result) {
if(err) {
//console.log("query " + err.toString());
exports.res = "Data NOT";
}
else {
console.log(result.rows);
module.exports.resul = result.rows;
}
done();
});
});
pool.end()
file app.js
var dataWithDB = require('./DataBase/ConnectToDb');
console.log(dataWithDB + " wit DB");
as a result deduces to me undefined wit DB but should data from db
Can an error in the scope? Data is sent if you specify at the end of the file module.exporst.result = "Example".
Here is what you should do: import a different callback function that you pass into your query. This callback will do whatever you want with result. As written, your method will not work and does not make sense.
You should encapsulate your connect to db code in a function which takes a callback.
Here is an example, hopefully you get the idea. :)
var pg = require("pg");
module.exports = (callback) => {
var pool = new pg.Pool({
host: "localhost",
port: "5432",
user: "postgres",
password: "111111",
database: "hrs"
});
pool.connect(function (err, client, done) {
if (err) {
console.log("connect " + err.toString());
} else {
let query = 'SELECT id, "idName", "idContact",' +
' "idExperience","idSkill", "dateAdded", "dateColloquy"' +
'FROM public."applicant ";'
client.query(query, function (err, result) {
if (err) {
//console.log("query " + err.toString());
exports.res = "Data NOT";
callback(err);
}
else {
console.log(result.rows);
callback(null, result);
}
done(); // Not sure what this does! :-o
});
}
});
// Is this trying to close it before we've connected?
// It should probably be up above...
pool.end()
}
var connectToDb = require('./DataBase/ConnectToDb');
connectToDb((err, result) => {
// This is a callback!
if(err) console.log(err)
else console.log(result)
})
Do a google search for: node.js callback pattern
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.