Cannot display row count in node.js

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?

Answers


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

Need Your Help

Hadoop passing variables to mapper and reducer

java hadoop

I'm a complete beginner with Hadoop. I've built Word Count, and I'm fairly sure I understand the basics, but I'm having trouble extending that to an actual problem. My (modified) code is below:

I need help to print the elements in this array?

java arrays

System.out.println("Here is the list by Category Type.");