0

I'm having problems trying to add rows to the variable x. I have not understood how to return a value from an anonymous function called by another function.

var pgClient = new pg.Client(connectionString);
pgClient.connect();
var query = pgClient.query("SELECT * from sceglie");

var x = [];

query.on("row", function(row,result){
    result.addRow(row);
    x.push(row);
});

console.log(x);
Luca Di Liello
  • 1,486
  • 2
  • 17
  • 34
  • 1
    you... don't. it's that simple. – Kevin B Dec 05 '16 at 18:57
  • @KevinB but is there a solution to create a generic function like function foo (query_string,DB_URL){} that returns the result of the query on this DB? – Luca Di Liello Dec 05 '16 at 19:03
  • The anonymous function will run asynchronously (everytime the "row" event occurs) and `console.log` will execute right away, so at that time `x` will always be empty. You'll need some sort of callback. – Duncan Lukkenaer Dec 05 '16 at 19:04
  • No, it simply is not possible to have a function that returns the result of an asynchronous action unless the asynchronous action was already complete before said function was called. – Kevin B Dec 05 '16 at 19:05
  • Another relevant canonical dupe: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – JohnnyHK Dec 05 '16 at 19:05
  • @JohnnyHK I don't think this is an exact duplicate as the question is not specifically about asynchronous JavaScript, but about retrieving the result of an PostgreSQL query. – Duncan Lukkenaer Dec 05 '16 at 19:21
  • @Duncan It actually is the same because the results of a PostgreSQL query are delivered asynchronously; so the `on` callback is async. – JohnnyHK Dec 05 '16 at 19:45
  • @JohnnyHK I've found that `client.query('SELECT * from sceglie', [], function (err, result) {})` will execute the query synchronously. So that could be an answer to this question, instead of some information about async JS. – Duncan Lukkenaer Dec 05 '16 at 20:16
  • @Duncan I don't mean to difficult, but the callback to `client.query` is also async. async callbacks for DB operations is a fundamental concept in node.js. – JohnnyHK Dec 05 '16 at 20:21
  • @JohnnyHK That's true, but that way he can use the full result of the query at once, which is what I think his goal was here. – Duncan Lukkenaer Dec 05 '16 at 20:26

1 Answers1

0

There is no way to do what you are trying to do. Javascript is a synchronous language in that it executes line by line. So this line:

console.log(x)

Will execute right away. The "on" function will only execute when it is called, so your log statement will always have the empty value.

Link to good article explaining JS environment

spartikus
  • 2,852
  • 4
  • 33
  • 38