Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning result from SELECT with node-postgres

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);
like image 738
magnudae Avatar asked Jul 03 '13 06:07

magnudae


1 Answers

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.

like image 185
Drasill Avatar answered Oct 15 '22 19:10

Drasill