I've been reading about NodeJS and callbacks but I've been unable to get the grasp of it. Wait for function Here they explain why this happens but I don't understand how to do it with 2 nested functions.
I have a function that calls another function that will select a row from PostgreSQL Simple as that. Problem is, my function that looks up this row always returns before the select finishes so it doesn't work.
function testing() {
var p=getTrackerId("123");
console.log(p);
}
function getTrackerId(id) {
var tracker_id="TEST";
pg.connect(conString, function(err, client, done) {
if(err) {
return console.error('error fetching client from pool', err);
}
tracker_id="THIS1";
var q = squel.select()
.from("access")
.where("unique_id = ?",id)
.toString();
client.query(q, function(err, result) {
if(result.rows[0]!=undefined){
tracker_id=result.rows[0].tracker_id;
}
done();
tracker_id="THIS3";
if(err) {
return console.error('error running query', err);
}
});
});
return tracker_id;
}
This function will always return "TEST" and, therefore, p will always be TEST. Any ideas on how to solve this issue?