Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

While booting my Node.js app, I want to make a couple of synchronous calls to the PostgreSQL database to check some things before continuing the control flow. How can I achieve this using the node-postgres package?

share|improve this question
up vote 3 down vote accepted

The only way to synchronize calls is to nest them in callbacks:

function init() {
  pg.connect('tcp://user@host/db', function(err, client, done) {
    client.query("SELECT column FROM table", function(err, result) {
      // check some things...
      client.query("SELECT column FROM other_table", function(err, result) {
        // check some other things...
        main(); // proceed with flow...
      }
    });
  }
}

function main() {
  // main logic
}

This can be a pain, and would be trivial in some other languages, but it is the nature of the beast.

share|improve this answer
    
nice comment: but it is the nature of the beast... Doubt this is a beast, though :) – luigi7up Jun 24 '13 at 14:55
    
So there is no way to reuse code? i.e have a function that makes a pg query and returns the results so I can call that function from different places. Is this possible? Thanks – Ryan Lee Jul 31 '14 at 4:17

I think this would be applicable.

share|improve this answer

Given that the call is inherently asynchronous, you'll need to manage it either via callbacks (the defacto Node style), async or via promises (Q, when.js, Bluebird, etc...) Please note that wrt to the accepted answer, callbacks are not the only way to do this.

share|improve this answer

brianc (author of node-postgres) commented here, that

"The only way to do sync queries is to use pg-native and use the sync variant of the methods. Using pure javascript client it is impossible to do sync queries because of how node works."

Hope this helps...

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.