Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node-Postgres query method not calling its callback function

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!

like image 724
DanB91 Avatar asked Oct 20 '22 23:10

DanB91


1 Answers

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();
});
like image 155
th317erd Avatar answered Oct 24 '22 10:10

th317erd