11

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);

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Just had to fully understand callbacks in javascript.
4

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();
});

Ref: http://nodeexamples.com/2012/09/21/connecting-to-a-postgresql-database-from-node-js-using-the-pg-module/

2 Comments

is it possible to return array of rows in a variable instead show in console?
inside "end" listener, you can return result by either 1. call a callback function - which will update response to requested sockets (using socket.io) ex: callback(result); 2. using "q" library ex: var q = require('q'); ... // wait for query data\n queryDb(params).then(function(data) { }); ... var queryDb = function(args) { var deferred = q.defer(); ... query.on('end', function(result) { deferred.resolve(result.rows); }); return deferred.promise; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.