Why is resultofgetCauses undefined? I'm not sure if the function is not returning currentCauses or if it not being assigned to resultofgetCauses . . . or if this has something to do with asynchronicity.
function getCauses(){
var currentCauses;
client = pg.connect(connectionString, function(err, client, done){
if(err) console.log(err);
client.query('SELECT * FROM causes', function(err, result){
//console.log(result.rows);
console.log('poo');
currentCauses=result.rows;
//console.log(currentCauses);
});
});
return currentCauses;
};
var resultofgetCauses = getCauses();
Yes since it's running asynchronously, by the time result.rows is assigned to the currentCauses variable, the line return currentCauses has already been executed thus the value is undefined.
You may want to do that as follow
var resulttofgetCauses;
function getCauses(){
var currentCauses;
client = pg.connect(connectionString, function(err, client, done){
if(err) console.log(err);
client.query('SELECT * FROM causes', function(err, result){
//console.log(result.rows);
console.log('poo');
currentCauses=result.rows;
//console.log(currentCauses);
resulttofgetCauses = currentCauses;
});
});
};
getCauses();
To be more specific with the answer, executing 'SELECT * FROM causes' sql does not give you the result right after its execution time. It takes at least 0.00something seconds to retrieve the data from database. So in the very short time between 'executing sql' and 'receiving requested data' JavaScript has already executed return currentCauses; while the correct data is still in the progress of retrieving. Because it's async and won't wait. There are good example code out there on the internet you may want to check out.
Plus It's a good practice to define function as follow
getCauses = function () { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With