Reputation: 1272
Having trouble getting results back from SELECT queries in node-postgres. Now rows are empty at the end of the codeblock. This select just returns a next value from a sequence in POSTGRESQL. I know that you can not retrieve results from callback, but are there anyone here who have used node-postgres(or any other database modules to node) that might know a fix?
client.connect();
var query = client.query("SELECT nextval(\'idgenerator\');");
var rows = [];
query.on('row', function(row, res) {
rows.push(row);
});
query.on('end', function(result) {
console.log(result.rowCount + ' rows were received');
});
//client.end();
console.log(rows);
Upvotes: 11
Views: 20079
Reputation: 606
If we did not call the result.addRow() method, the rows array would be empty in the end event.
var query = client.query("SELECT firstname, lastname FROM emps ORDER BY lastname, firstname");
query.on("row", function (row, result) {
result.addRow(row);
});
query.on("end", function (result) {
console.log(JSON.stringify(result.rows, null, " "));
client.end();
});
Upvotes: 4
Reputation: 4016
You'll have to learn javascript / nodejs, and event programming.
query.on('row', function() { /*CODE*/ })
means : "when a row is read, execute CODE".
This is asynchronous; so query.on() register the event, and returns.
So when console.log(rows)
is called, rows is still empty, because no 'row' event has been triggered on query, yet.
You should try putting 'console.log(rows)' in the body of the query.on('end') event handler.
Everywhere in the code, also, you should write some console.log
. You'll see the asynchronous thing.
Upvotes: 7