5

I have the following code which uses node-postgres:

    var client = new pg.Client(conString);
    client.connect(function(err) {
        if(err) {

            throw new Error(console.error('could not connect to postgres '+  err));
        }

    });
    client.query('select * from public.spatial_ref_sys', function(err, result){ 
        console.log('ffdafda');
        throw new Error('kokpokopko');
    });

I would think when this code executes, 'ffdafda' would be printed to the screen and an error with message 'kokpokopko' would be thrown. I even stuck a in breakpoint which never breaks in the debugger. Since these things never occur, I am assuming the callback is never called.

Is there some sort of option I need in order to get the callback called? I am reading the documentation and I see nothing.

It is important to note client.query is being called. I have proved it by checking its return value.

Thank you very much!

Chris Travers
  • 25,424
  • 6
  • 65
  • 182
DanB91
  • 1,399
  • 1
  • 13
  • 23
  • I had similar symptom, turned out I had an older version of pg installed which failed silently when trying to query. Installing 8+ fixed the issue for me. – Josh Diehl Jun 11 '20 at 02:43

1 Answers1

3

I know this is 10 months old, but this one just bit me, so I am posting the solution.

The callback for a query only ever seems to fire if an error was thrown, or a row was received. In my particular case I was only ever using "insert" queries. The result I got was that my callback was never fired (if provided), and also both the "error" and "row" events never fired. The only event I got to fire was "end". I suggest the following for a solution:

pg.connect(conString, function(err, client, done) {
  if(err)
    return console.error('error fetching client from pool', err);

  var q = client.query("INSERT INTO wddata (id, type, word) VALUES('456','n','a value')", function(err, result) {
    //this callback never fires for some queries
    if(err)
      return console.error('error running query', err);

    console.log(result.rows[0].number);
  });
  q.on('end', function() {
    //This event callback always fires
    console.log('Finished with query');
  });
  done();
});
th317erd
  • 304
  • 3
  • 11