11

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?

Dejan
  • 7,717
  • 7
  • 57
  • 105

6 Answers6

10

You can use the pg-native or pg-sync package.

Johannes Griebenow
  • 499
  • 1
  • 7
  • 15
7

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.

Michael Payne
  • 508
  • 5
  • 13
  • 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 04:17
  • Yeah... This is by far the ugliest Postgres-involving code I've ever written. But +1 for correct answer. – sudo Jan 22 '18 at 19:11
  • @Michael Payne and if i need to insert data into the db from data generated during the main() flow? – justcode Apr 24 '18 at 13:44
  • Sometimes, in a constructor for example, we want synchronous operations... Bad point for node-postgres ! – fred727 Feb 03 '20 at 14:51
1

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.

alphadogg
  • 12,414
  • 7
  • 53
  • 84
1

You can do this by using pg-pool in combination with asyncawait:

var suspendable = async (function defn(a, b) {
 var name1 = await(pool.query('select $1::text as name', ['foo']));
 console.log(name1.rows[0].name, 'says hello');
 var name2 = await(pool.query('select $1::text as name', ['bar']));
 console.log(name2.rows[0].name, 'says hello');
});

suspendable();
Black
  • 4,711
  • 6
  • 60
  • 84
0

I think this would be applicable.

eonil
  • 79,444
  • 75
  • 307
  • 502
0

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...

muelleth
  • 163
  • 1
  • 4