1

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?

1 Answer 1

1

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');
            }
        });
    }
});
Sign up to request clarification or add additional context in comments.

Comments

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.