I would think this would be simple...however I am smashing my head against it. I am calling a function in my 'main' (Node.js) script to do a query on a Postgres database. I simply wish to return an array (or even better an 'array of arrays'), from the function so I can process those variables. The Postgres processing is handled in a different .js file...I would think this code should work, however it does not:
my database .js file ('queries.js'):
const config = {
...
//various settings
...
};
const Pool = require('pg').Pool;
const pool = new Pool(config);
const getUsers = function(request, response) {
pool.query('SELECT * FROM users', (error, results) => {
if (error) {
throw error
}
// response.status(200).json(results.rows)
return _findings = ["value1", "value2"];
})
}
module.exports = {
getUsers
}
my 'main' script:
const db = require('./routes/queries');
app.get('/lookup', function (req, res) {
var _findings = [];
db.getUsers;
console.log("I FOUND A LOOKUP...!!!" + _findings[0] + _findings[1]);
});
I do not get errors however the returned array variables ('_findings') are reported as "undefined". I know the Postgres query is operative because if I 'un-comment' the "response.status(200).json(results.rows)" it returns the data properly. I want to be able to take the returned array variables into my calling function and then do additional processing from there. Is the problem caused by attempting to 'return' from a different .js file...? I thank you in advance for any suggestions.
OK based upon given advice I have made some modifications...the following code was inserted into my 'main' script...and it IS functional:
async function mytest() {
// create a new promise inside of the async function
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve(true), 1000) // resolve
});
// wait for the promise to resolve
let result = await promise;
// console log the result (true)
console.log(result);
}
app.get('/lookup', function (req, res) {
mytest();
});
If I add the 'async' function to my database ('queries.js') file to perform the query:
async function getSingle(req, res) {
// create a new promise inside of the async function
let promise = new Promise((resolve, reject) => {
pool.query('SELECT * FROM users', (error, results) => {
if (error) {
reject("db query failed"); //rejected
}
resolve(response.status(200).json(results.rows)); //fulfilled
})
});
// wait for the promise to resolve
let result = await promise;
}
However if I change my 'main' script as this:
app.get('/lookup', function (req, res) {
db.getSingle();
});
I get a "db.getSingle is not a function" error. Any help on proper syntax is appreciated on how to call the async database function...as well as if the actual async function is correct...I THINK it is...but I am new to the concept of 'promise/await/async'...thank you in advance.
OK...this code is actually working...! In my database ('queries.js') script I have:
function getFinals() {
return new Promise(function(resolve, reject) {
pool.query('SELECT * FROM users', (error, results) => {
if (error) {
reject(new Error('Ooops, something broke!'));
} else {
resolve(results.rows);
}
}) //pool.query
});
}
In my main script I call:
app.get('/lookup', function (req, res) {
db.getFinals()
.then(function(value) {
console.log('Async success!', value);
})
.catch(function(err) {
console.log('Caught an error!', err);
});
});
I actually get the data from the database query returned to my calling function...! I feel like I learned something today.
Also need to determine how to return an 'array of arrays' from the async function...that is probably tomorrow's project...
Thanks to all the responses I received...all great help and much appreciated!