Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

I am trying to run the following bit of code in node.js to display the number of tables in a postgresql database:

var pg = require('pg'); 
var conString = "postgres://login:pwd@localhost/DB";
var client = new pg.Client(conString);

client.connect(function(err) {
    if (err) {
        console.error('Could not connect to DB', err);
    } else {
        console.log('Could connect to DB');
        client.query("SELECT * FROM pg_catalog.pg_tables", function(err, result) {
            if (err) {
                console.error('Error with table query', err);
            } else {
                var cnt = result.rows.length;
                console.log("Row count: " + cnt.toString());
            }
        });
        console.log('After query');
        client.end();
    }
});

Unfortunately, only the following is displayed in the console:

Could connect to DB
After query

Why isn't the row count line displayed? How can I find out what the issue is?

share|improve this question
up vote 0 down vote accepted

Since client.query is asynchronous, client.end() will be called before the query has a chance to return a result

Try moving client.end() inside of your async function to client.query. Then it will only be called after result.rows has been logged to console, like so:

client.connect(function(err) {
    if (err) {
        console.error('Could not connect to DB', err);
    } else {
        console.log('Could connect to DB');
        client.query("SELECT * FROM pg_catalog.pg_tables", function(err, result) {
            if (err) {
                console.error('Error with table query', err);
            } else {
                var cnt = result.rows.length;
                console.log("Row count: " + cnt.toString);
                client.end();
                console.log('After query');
            }
        });
    }
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.